var tempText = [];
var classNum = event.relatedTarget.getElementsByClassName('text');
var newCont = document.createElement('div');
for(var i = 0; i < classNum.length; i++){
tempText.push(event.relatedTarget.getElementsByClassName('text')[i].textContent);
}
for(var i = 0; i < tempText.length; i++){
var pText = document.createElement('p').appendChild(tempText);
newCont.appendChild(pText[i]);
}
var placement = document.getElementById('toolbar')[0];
placement.appendChild(newCont);
我想把输出作为:
12-31.23
答案 0 :(得分:1)
您可以将String#replace
方法与计数器变量一起使用。
function format1(txtnumber, txtformat) {
// initialize counter varibale
var i = 0;
// replace all # and x from format
return txtformat.replace(/[#x]/g, function() {
// retrive corresponding char from number string
// and increment counter
return txtnumber[i++];
})
}
console.log(
format1("123123", "xx-#x.#x")
)
&#13;
或者使用单个for循环,不需要嵌套循环使其更复杂。
function format1(txtnumber, txtformat) {
// initialize string as empty string
var fin = '';
// iterate over format string
for (var i = 0, j = 0, len = txtformat.length; i < len; i++) {
// if char is x or # concatenate the number
// from string and increment the counter
// else return the existing character
fin += txtformat[i] == 'x' || txtformat[i] == '#' ? txtnumber[j++] : txtformat[i];
}
return fin;
}
console.log(
format1("123123", "xx-#x.#x")
);
&#13;