admin管理员组文章数量:1336633
What is the shortest way to negate all elements in a javascript array, with reasonable efficiency?
For example, the solution would convert [0, 18, -1, -2, 1, 3]
to [0, -18, 1, 2, -1, -3]
The solution does not need to handle any values that are NaN/undefined/null, because the array I need this for does not contain any of those values.
Here is what I normally do (with array array
):
for(var i = 0; i < array.length; i++) {
array[i]*=-1
}
The problem is that I need to invert this array in several places, so don't want to reuse large code.
Thanks
What is the shortest way to negate all elements in a javascript array, with reasonable efficiency?
For example, the solution would convert [0, 18, -1, -2, 1, 3]
to [0, -18, 1, 2, -1, -3]
The solution does not need to handle any values that are NaN/undefined/null, because the array I need this for does not contain any of those values.
Here is what I normally do (with array array
):
for(var i = 0; i < array.length; i++) {
array[i]*=-1
}
The problem is that I need to invert this array in several places, so don't want to reuse large code.
Thanks
Share edited Jul 5, 2016 at 2:38 user31415 asked Jul 5, 2016 at 2:21 user31415user31415 4667 silver badges16 bronze badges 1- 2 What did you try? Shouldn't have been difficult to at least make an attempt and show that attempt rather than ask how to do it from scratch – charlietfl Commented Jul 5, 2016 at 2:26
2 Answers
Reset to default 6That would be array.map
returning the negative of each value. Adding in arrow function for an even shorter syntax.
var negatedArray = array.map(value => -value);
negate all elements in a javascript array
I think you are referring to negate only the positive number.
var _myArray = [0, 18, -1, -2, 1, 3]
var _invArray = [];
_myArray.forEach(function(item){
item >0 ?(_invArray.push(item*(-1))) :(_invArray.push(item))
})
console.log(_invArray);
JSFIDDLE
本文标签: How to negate all elements in javascript arrayStack Overflow
版权声明:本文标题:How to negate all elements in javascript array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742401499a2467974.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论