[英]Get an element of array and add to other elements in Javascript
我有两个长度相同的 arrays。 我想从一个数组中获取一个元素,并继续将它的值 (+1) 添加到每个其他元素,直到值为 0。
这是我的代码:
const update = (source, target, index) => {
const keys = Object.keys(source)
let value = source[target][index]
source[target][index] = 0
while (value--) {
source[target][index++]++
if (index === source[target].length) {
index = 0
target = keys[(keys.indexOf(target) + 1) % keys.length]
}
}
return source
}
console.log(update({a: [0, 0, 0, 8, 0], b: [0, 0, 0, 0, 0]}, 'a', 3))
answer: { a: [ 1, 0, 0, 1, 1 ], b: [ 1, 1, 1, 1, 1 ] }
所以它的作用是;
它采用数组 a 的索引3 ,即 8 --> a[3] 变为 0
继续向自身和 arrays 的其他元素添加 (+1),直到 a[3] 结束。
但这就是挑战,我想传递其他数组的最后一个元素(可以是数组a或b )并且从不添加 +1。 所以我的回答应该是:
answer: { a: [ 1, 1, 0, 1, 1 ], b: [ 1, 1, 1, 1, 0 ] } --> last element of b not changed!
const update = (source, target_param, index_param) => { const keys = Object.keys(source) let target = target_param let index = index_param let value = source[target][index] source[target][index] = 0 while (value--) { source[target][index++]++ if (index === source[target].length || target.== target_param && index === source[target].length - 1) { index = 0 target = keys[(keys.indexOf(target) + 1) % keys.length] } } return source } console:log(update({a, [0, 0, 0, 8, 0]: b, [0, 0, 0, 0, 0]}, 'a', 3))
最重要的变化是条件(index === source[target].length || target.== target_param && index === source[target].length - 1)
而不是改变 function 参数。
我强烈建议永远不要改变 function 参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.