目录
Array.reduce()和 Array.reduceRight()
Array.from({ length: 10 }, (item, index) => index); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Array.of((1,2,3,4,5)); //[1, 2, 3, 4, 5]
value instanceof Array
Array.isArray(value)
const lazy = ['one', 'two', 'three', 'four'];
Array.from(lazy.keys); //[0, 1, 2, 3]
Array.from(lazy.values); //["one", "two", "three", "four"]
Array.from(lazy.entries()); //[[0, "one"][1, "two"][2, "three"][3, "four"]]
const zeroes = [0, 0, 0, 0, 0];
// 用5填充整个数组
zeroes.fill(5); //[5, 5, 5, 5, 5]
zeroes.fill(0); // 重置
// 用6填充索引大于等于3的元素
zeroes.fill(6, 3); //[0, 0, 0, 6, 6]
zeroes.fill(0); // 重置
// 用7填充大于等于1且小于3的元素
zeroes.fill(7, 1, 3); //[0, 7, 7, 0, 0]
zeroes.fill(0); // 重置
// 用8填充索引大于等于1且小于4的元素
// (-4 + zeroes.length = 1)
// (-1 + zeroes.length = 1)
zeroes.fill(8, -4, -1); //[0, 8, 8, 8, 0]
zeroes.fill(0); // 重置
// fill() 静默忽略超出数组边界、零长度及方向相反的索引范围
// 索引过低,忽略
zeroes.fill(1, -10, -6); //[0, 0, 0, 0, 0]
// 索引过高忽略
zeroes.fill(1, 10, 15); //[0, 0, 0, 0, 0]
// 索引反向,忽略
zeroes.fill(2, 4, 2); //[0, 0, 0, 0, 0]
// 索引部分可用,填充可用部分
zeroes.fill(4, 3, 10); //[0, 0, 0, 4, 4]
let ints;
reset = () => ints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
reset(); //重置
// 从inits中复制0开始的内容,插入到索引5的位置
// 在源索引或目标索引到达数组边界时停止
ints.copyWithin(5); //[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
reset(); // 重置
// 从ints中复制索引5开始的内容,插入到索引0开始的位置
ints.copyWithin(0, 5); //[5, 6, 7, 8, 9, 5, 6, 7, 8, 9]
reset(); // 重置
// 从int中复制索引0开始到索引3结束的内容
// 插入到索引4的位置
ints.copyWithin(4, 0, 3); //[0, 1, 2, 3, 0, 1, 2, 7, 8, 9]
reset(); // 重置
// JavaScript 引擎在插值钱回完整复制范围内的值
// 因此复制期间不存在重写的风险
ints.copyWithin(2, 0, 6); //[0, 1, 0, 1, 2, 3, 4, 5, 8, 9]
reset(); // 重置
// 支持负索引值,与fill()相对于数组末尾计算正向索引的过程是一样的
ints.copyWithin(-4, -7, -3); //[0, 1, 2, 3, 4, 5, 3, 4, 5, 6]
let colors = ['red', 'blue', 'yellow'];
colors.valueOf(); // ["red", "blue", "yellow"]
colors.toString(); // "red,blue,yellow"
colors.toLocaleString(); // 'red,blue,yellow'
let arr = [1, 2, 3];
console.log(arr.join()); // 1,2,3
console.log(arr.join("-")); // 1-2-3
console.log(arr); // [1, 2, 3](原数组不变)
实现重复字符串
function repeatString(str, n) {
return new Array(n + 1).join(str);
}
console.log(repeatString("abc", 3)); // abcabcabc
console.log(repeatString("Hi", 5)); // HiHiHiHiHi
注意,如果数组中的某一项是 null 或 undefined, 则在 join() toLocaleString() toString() valueOf() 返回的结果以空字符串表示
const arr = ["Lily","lucy","Tom","lazy"];
const count = arr.push("Jack","Sean");
console.log(count); // 6
console.log(arr); // ["Lily", "lucy", "Tom", "lazy", "Jack", "Sean"]
const item = arr.pop();
console.log(item); // Sean
console.log(arr); // ["Lily", "lucy", "Tom", "lazy", "Jack"]
const arr = ["Lily", "lucy", "Tom", "lazy"];
const count = arr.unshift("Jack", "Sean");
console.log(count); // 6
console.log(arr); //["Jack", "Sean", "Lily", "lucy", "Tom", "lazy"]
const item = arr.shift();
console.log(item); // Jack
console.log(arr); // ["Sean", "Lily", "lucy", "Tom", "lazy"]
let arr = [13, 24, 51, 3];
console.log(arr.reverse()); //[3, 51, 24, 13]
console.log(arr); //[3, 51, 24, 13](原数组改变)
let arr1 = ["a", "d", "c", "b"];
console.log(arr1.sort()); // ["a", "b", "c", "d"]
let arr2 = [13, 24, 51, 3];
console.log(arr2.sort()); // [13, 24, 3, 51] 两位数字先比较第一位再比较第二位
console.log(arr2); // [13, 24, 3, 51](原数组被改变)
为了解决上述问题,sort()方法可以接收一个比较函数作为参数,以便我们指定哪个值位于哪个值的前面。比较函数接收两个参数
function compare(value1, value2) {
return value1 - value2;
}
let arr = [13, 24, 51, 3];
console.log(arr.sort(compare)); // [3, 13, 24, 51]
如果需要通过比较函数产生降序排序的结果,只要交换比较函数返回的值即可:
function compare(value1, value2) {
return value2 - value1;
}
let arr = [13, 24, 51, 3];
console.log(arr.sort(compare)); // [51, 24, 13, 3]
const arr = [1,3,5,7];
const arrCopy = arr.concat(9,[11,13]);
console.log(arrCopy); //[1, 3, 5, 7, 9, 11, 13]
console.log(arr); // [1, 3, 5, 7](原数组未被修改)
const arrCopy2 = arr.concat([9,[11,13]]);
console.log(arrCopy2); //[1, 3, 5, 7, 9, Array[2]]
console.log(arrCopy2[5]); //[11, 13]
const arr = [1,3,5,7,9,11];
const arrCopy = arr.slice(1);
const arrCopy2 = arr.slice(1,4);
const arrCopy3 = arr.slice(1,-2);
const arrCopy4 = arr.slice(-4,-1);
console.log(arr); //[1, 3, 5, 7, 9, 11](原数组没变)
console.log(arrCopy); //[3, 5, 7, 9, 11]
console.log(arrCopy2); //[3, 5, 7]
console.log(arrCopy3); //[3, 5, 7]
console.log(arrCopy4); //[5, 7, 9]
// arrCopy只设置了一个参数,也就是起始下标为1,所以返回的数组为下标1(包括下标1)开始到数组最后。
// arrCopy2设置了两个参数,返回起始下标(包括1)开始到终止下标(不包括4)的子数组。
// arrCopy3设置了两个参数,终止下标为负数,当出现负数时,将负数加上数组长度的值(6)来替换该位置的数,因此就是从1开始到4(不包括)的子数组。
// arrCopy4中两个参数都是负数,所以都加上数组长度6转换成正数,因此相当于slice(2,5)。
let arr = [1,3,5,7,9,11];
let arrRemoved = arr.splice(0,2);
console.log(arr); //[5, 7, 9, 11]
console.log(arrRemoved); //[1, 3]
let arrRemoved2 = arr.splice(2,0,4,6);
console.log(arr); // [5, 7, 4, 6, 9, 11]
console.log(arrRemoved2); // []
let arrRemoved3 = arr.splice(1,1,2,4);
console.log(arr); // [5, 2, 4, 4, 6, 9, 11]
console.log(arrRemoved3); //[7]
Array.indexOf()和 Array.lastIndexOf()
const arr = [1,3,5,7,7,5,3,1];
console.log(arr.indexOf(5)); //2
console.log(arr.lastIndexOf(5)); //5
console.log(arr.indexOf(5,2)); //2
console.log(arr.lastIndexOf(5,4)); //2
console.log(arr.indexOf("5")); //-1
Array.includes() ES7
const arr = [1,3,5,7,7,5,3,1];
arr.includes(3); // true
arr.includes(4); // false
Array.find()和Array.findIndex()
const people = [
{
name: 'lazy',
age: 25
},
{
name: 'lazy',
age: 23
},
{
name: 'make',
age: 20
}
]
people.find((element, index, array) => element.age > 21); //{name: "lazy", age: 25}
people.findIndex((element, index, array) => element.age > 21); //0
找到匹配项后,这两个方法都不再继续搜索
const arr = [1, 2, 3, 4, 5];
arr.forEach(function(x, index, a){
console.log(x + '|' + index + '|' + (a === arr));
});
// 输出为:
// 1|0|true
// 2|1|true
// 3|2|true
// 4|3|true
// 5|4|true
const arr = [1, 2, 3, 4, 5];
const arr2 = arr.map(function(item){
return item*item;
});
console.log(arr2); //[1, 4, 9, 16, 25]
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const arr2 = arr.filter(function(x, index) {
return index % 3 === 0 || x >= 8;
});
console.log(arr2); //[1, 4, 7, 8, 9, 10]
const arr = [1, 2, 3, 4, 5];
const arr2 = arr.every(function(x) {
return x < 10;
});
console.log(arr2); //true
const arr3 = arr.every(function(x) {
return x < 3;
});
console.log(arr3); // false
const arr = [1, 2, 3, 4, 5];
const arr2 = arr.some(function(x) {
return x < 3;
});
console.log(arr2); //true
const arr3 = arr.some(function(x) {
return x < 1;
});
console.log(arr3); // false
这两个方法都会实现迭代数组的所有项,然后构建一个最终返回的值。reduce()方法从数组的第一项开始,逐个遍历到最后。而 reduceRight() 则从数组的最后一项开始,向前遍历到第一项。
这两个方法都接收两个参数:
传给 reduce()和 reduceRight() 的函数接收 4 个参数:前一个值、当前值、项的索引和数组对象。这个函数返回的任何值都会作为第一个参数自动传给下一项。第一次迭代发生在数组的第二项上,因此第一个参数是数组的第一项,第二个参数就是数组的第二项。
下面代码用 reduce() 实现数组求和,数组一开始加了一个初始值10。
const values = [1,2,3,4,5];
const sum = values.reduceRight(function(prev, cur, index, array){
return prev + cur;
},10);
console.log(sum); //25
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代
我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco
我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby数组,我们在StackOverflow上找到一
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer