我正在使用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函数。

你能帮帮我吗?


当前回答

(1, 2, 3, 4, 5, 6, 7, 8, 8]。slice(0,3) = While返回前3个元素。

答:(1、2、3)

工作原理:

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

其他回答

试着从列表中获取前n个元素:

const slicedList = list.slice(0, n);

例子: Const list = [1,2,3,4,5] console.log(列表。slice(0,3)) //返回[1,2,3] console.log(列表。slice(0, 10)) //返回[1,2,3,4,5],因为这是前10个元素中所有的元素

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"]

知道更多

用LInQer你可以做到:

Enumerable.from(list).take(3).toArray();

下面的方法对我很有效。

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

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

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