返回嵌套数组的前两个索引的更简单方法?

时间:2018-11-05 21:13:07

标签: javascript lodash

除了创建for循环之外,还有没有更简单的方法来返回数组的前两个索引?可能是lodash吗?

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

for (let i = 0; i < animals.length; i++){ 
   console.log(animals[i].slice(0,2));
}

3 个答案:

答案 0 :(得分:3)

您可以使用map将数组转换为具有正确切片的数组:

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

console.log(animals.map(a => a.slice(0, 2)));

答案 1 :(得分:1)

lodash引入了有趣的方法invokeMap(),该方法允许代码最短:

public class ErrorPageConfigurationStartup
{   
    public void Configure(IApplicationBuilder app)
    {
        app.UseExceptionHandler("/Home/Error");           
    }

    public void ConfigureDevelopment(IApplicationBuilder app)
    {
        app.UseDeveloperExceptionPage();
    }
}

但是如上所述,也许最好使用经典的console.log(_.invokeMap(sourceArray, 'slice', 0, 2)) 来提高可读性(因为众所周知)

答案 2 :(得分:0)

没有lodash,您只需映射...

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

const first2 = animals.map(a => a.slice(0, 2))

console.log(first2)