1、js遍历数组用逗号连接
var arr = [{ name: 'Tony' }, { name: 'Echo' }];
function getTextByJs() {
var str = '';
for (var i = 0; i < arr.length; i++) {
str += arr[i].name + ',';
}
if (str.length > 0) {
str = str.substr(0, str.length - 1);
}
return str;
}
console.log(getTextByJs());
2、拓展思路,取出数组中的最大值(split,sort)
var maxArr = [
{ id: '1', score: 99 },
{ id: '2', score: 98 },
{ id: '3', score: 50 },
{ id: '4', score: 100 },
];
function getMaxScore() {
var maxStr = '';
for (var i = 0; i < maxArr.length; i++) {
maxStr += maxArr[i].score + ',';
}
if (maxStr.length > 0) {
maxStr = maxStr.substr(0, maxStr.length - 1);
}
var maxNum = maxStr.split(',').sort((a, b) => b - a);
return maxNum[0];
}
console.log(getMaxScore());
3、字符串数组转数组(map)
let arr = ['1', '2', '3'];
let arr2 = arr.map((item) => {
return Number(item);
});
console.log(arr2);