我正在使用Javascript(ES6) /FaceBook反应,并试图获得大小不同的数组的前3个元素。我想做Linq take(n)的等效。

在我的Jsx文件中我有以下内容:

var items = list.map(i => {
  return (
    <myview item={i} key={i.id} />
  );
});

然后得到我尝试的前3个项目

  var map = new Map(list);
    map.size = 3;
    var items = map(i => {
      return (<SpotlightLandingGlobalInboxItem item={i} key={i.id} />);
    });

这并没有起作用,因为map没有一个set函数。

你能帮帮我吗?


当前回答

slice()方法将数组部分的浅拷贝返回到从开始到结束(不包括end)选择的新数组对象中,其中start和end表示该数组中项目的索引。原始数组将不会被修改。

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

知道更多

其他回答

可以使用数组索引进行过滤。

var months = ['Jan', 'March', 'April', 'June']; month = Months .filter((month,idx) => idx < 2) console.log(个月);

arr.length = n

这可能令人惊讶,但数组的长度属性不仅用于获取数组元素的数量,而且它也是可写的,可以用来设置数组的长度MDN链接。这将改变数组。

如果你不关心不可变性或不想分配内存,例如对于游戏来说,这将是最快的方法。

清空数组

arr.length = 0

slice()方法将数组部分的浅拷贝返回到从开始到结束(不包括end)选择的新数组对象中,其中start和end表示该数组中项目的索引。原始数组将不会被修改。

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

知道更多

使用切片法

javascript slice()方法将数组的一部分返回到一个从开始到结束选择的新数组对象中,其中start和end表示该数组中项目的索引。原始数组将不会被修改。

语法:slice(start, end)

假设我们有一个包含7个元素的数组[5,10,15,20,25,30,35],我们想要该数组的前5个元素:

let array = [5,10,15,20,25,30,35]
let newArray = array.slice(0,5)

console.log(newArray)

下面的方法对我很有效。

array.slice( where_to_start_deleting, array.length )

这里有一个例子

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.slice(2, fruits.length);
//Banana,Orange  ->These first two we get as resultant