我有一个问题,我无法呈现arrya.map()中编写的任何内容。外汇:
var array = [4,6,7,8,9];
var newVal= 0;
我这样做:
array.map(function(x){
return [ '<span class="xClass">',
x, // the xClass shows up with no value in the DOM, however I see the value when debugging
'</span>'].join('');
});
因此,我尝试了类似的操作:
array.map(function(x){
newVal += x;
});
return [
'<span class="xClass">',
newVal,
'</span>'
].join('');
但是上面的代码给了我newVal
数字一个奇怪的值,不确定如何计算。有没有一种方法可以存储映射的值,然后稍后在return()中使用它们?
这就是我希望得到的o / p:
<span>4</span>
<span>6</span>
<span>7</span>
<span>8</span>
<span>9</span>
答案 0 :(得分:0)
如果我没有误解您的问题,那么您需要类似的东西。
function
中,例如getSpanWithValue()
newVal = 0
newVal
并将其分配给变量,例如mapped_result
mapped_result
在<span>
之间连接+
。
function getSpanWithValue() {
var array = [4, 6, 7, 8, 9];
var newVal = 0;
var mapped_result = array.map(function(x) {
newVal += x;
return newVal;
});
return ['<span class="xClass">' + mapped_result + '</span>'].join('');
}
console.log(getSpanWithValue())
用于多个 <span>
function getSpanWithValue() {
var array = [4, 6, 7, 8, 9];
var newVal = 0;
var mapped_result = array.map(function(x) {
newVal += x;
return ['<span class="xClass">' + newVal + '</span>'];
});
return mapped_result.join(' ');
}
console.log(getSpanWithValue())