I have a few arrays that are laid out like so:
我有一些像这样布局的数组:
var row1 = [4,6,4,0,9];
var row2 = [5,2,0,8,1];
var row3 = [2,0,3,1,6];
I want to replace any values that have 0 with a null value. so they would look like:
我想用0替换任何值为0的值。所以它们看起来像:
var row1 = [4,6,4,,9];
var row2 = [5,2,,8,1];
var row3 = [2,,3,1,6];
Any ideas? Basically what I'm trying to do is loop through each value of the array, check to see if it equals 0, and if so replace it with a null value.
有任何想法吗?基本上我要做的是循环遍历数组的每个值,检查它是否等于0,如果是这样,用空值替换它。
Thanks in advance.
提前致谢。
3 个解决方案
#1
2
You could do this:
你可以这样做:
var row1 = [4,6,4,0,9];
var row2 = [5,2,0,8,1];
var row3 = [2,0,3,1,6];
var arrRows = [row1, row2, row3];
for (var i = 0; i < arrRows.length; i++) {
for (var j = 0; j < arrRows[i].length; j++) {
if (arrRows[i][j] == 0) {
arrRows[i][j] = null;
}
}
}
Demo: http://jsfiddle.net/npYr2/
演示:http://jsfiddle.net/npYr2/
#2
5
You can use Array.prototype.map
:
您可以使用Array.prototype.map:
row1 = row1.map(function(val, i) {
return val === 0 ? null : val;
});
http://jsfiddle.net/6Mz38/
#3
0
Another possibility is the following
另一种可能性如下
var rows = [row1, row2, row3];
rows = rows.map(function(x){ return x.map(function(y){ return y === 0? null: y})});
#1
2
You could do this:
你可以这样做:
var row1 = [4,6,4,0,9];
var row2 = [5,2,0,8,1];
var row3 = [2,0,3,1,6];
var arrRows = [row1, row2, row3];
for (var i = 0; i < arrRows.length; i++) {
for (var j = 0; j < arrRows[i].length; j++) {
if (arrRows[i][j] == 0) {
arrRows[i][j] = null;
}
}
}
Demo: http://jsfiddle.net/npYr2/
演示:http://jsfiddle.net/npYr2/
#2
5
You can use Array.prototype.map
:
您可以使用Array.prototype.map:
row1 = row1.map(function(val, i) {
return val === 0 ? null : val;
});
http://jsfiddle.net/6Mz38/
#3
0
Another possibility is the following
另一种可能性如下
var rows = [row1, row2, row3];
rows = rows.map(function(x){ return x.map(function(y){ return y === 0? null: y})});