gpt4 book ai didi

Javascript:从功能上拼接出多组数组

转载 作者:行者123 更新时间:2023-11-30 09:26:09 25 4
gpt4 key购买 nike

假设我有一个对象,它包含 3 个不同大小的数组,其中字符串作为它们各自的一些元素类型,但也包含您不想迭代的冗余属性:例如如下:

let testobj = {
prop1: ['a1','a2','a3'],
prop2: ['a4','a5'],
prop3: ['a7'],
somepropthatyoudontwanttoiterate: 'hithere!'
}

当务之急是,如果我想拼接一个可能存在于这三个数组中任何位置的特定值,我可以这样做:

let a = 'a7'
for (let i=0; i<testobj.prop1.length; i++){
if (a == testobj.prop1[i])
testobj.prop1.splice(i, 1)
}
for (let i=0; i<testobj.prop2.length; i++){
if (a == testobj.prop2[i])
testobj.prop2.splice(i, 1)
}
for (let i=0; i<testobj.prop3.length; i++){
if (a == testobj.prop3[i])
testobj.prop3.splice(i, 1)
}

这很讨厌,而且极易出错,而且从长远来看可扩展性不强。

使用高阶函数来解决此问题的最佳函数式方法是什么?例如.map、.reduce、.sort、.filter?

最佳答案

您可以通过获取数组所需值的索引来获取对象和拼接的值。

虽然数组中只需要一个元素,但您可以采用 Array#some如果元素被拆分,则提前返回。

var testobj = { foo: 42, prop1: ['a1','a2','a3'], prop2: ['a4','a5'], prop3: ['a7'] },
value = 'a7';

Object
.values(testobj)
.some(a => Array.isArray(a) && a.includes(value) && a.splice(a.indexOf(value), 1));

console.log(testobj);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于Javascript:从功能上拼接出多组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48986062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com