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

你能帮帮我吗?


当前回答

也许我错过了一些东西,但感觉像踢开了一扇门,建议使用splice()?当然,重要的是要记住这将修改数组。

const myArray = [ '一',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ', ] myArray.splice (3) console.log (myArray) //期望输出:['one', 'two', 'three']

也可以获取数组中被保留元素之外的元素:

const myArray = [ '一',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ', ] const afterFirstThree = myArray.splice(3) console.log (myArray) //期望输出:['one', 'two', 'three'] console.log (afterFirstThree) / /预期的输出:[“4”、“5”、“6”、“7”) //如果n大于myArray。整个数组的长度被保留,如果试图获取返回值,它将是一个空数组

其他回答

虽然这个问题很老了,但到2021年,将会有一个完整的LINQ实现,用ECMAScript (javascript)的最新特性编写对象。

Github存储库是:https://github.com/IlanAmoyal/WebPartyLinq

也许我错过了一些东西,但感觉像踢开了一扇门,建议使用splice()?当然,重要的是要记住这将修改数组。

const myArray = [ '一',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ', ] myArray.splice (3) console.log (myArray) //期望输出:['one', 'two', 'three']

也可以获取数组中被保留元素之外的元素:

const myArray = [ '一',' 2 ',' 3 ',' 4 ',' 5 ',' 6 ',' 7 ', ] const afterFirstThree = myArray.splice(3) console.log (myArray) //期望输出:['one', 'two', 'three'] console.log (afterFirstThree) / /预期的输出:[“4”、“5”、“6”、“7”) //如果n大于myArray。整个数组的长度被保留,如果试图获取返回值,它将是一个空数组

试着从列表中获取前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个元素中所有的元素

要获取数组的前n个元素,使用

const slicedArray = array.slice(0, n);

用LInQer你可以做到:

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