我是JS的初学者,只是想了解下面代码中发生了什么。可能它有点愚蠢但是 - 好吧,就像我说的那样,我是初学者;)
首先它只是拆分数组,它是<merge>
<View />
<Button />
</merge>
函数的参数。
所以,在这个阶段,一切都看起来不错。但是,当我打电话给makeFriendlyDates(['2016-07-01', '2016-08-04']);
时,只有存在的原因是将数字更改为月份名称,它也会以某种方式更改function changeToFriendly(arr1);
。
因此,如果我注释掉这一行:newArr
那么//changeToFriendly(newArr);
应该是什么,但是如果newArr
被调出,它会以某种方式改变changeToFriendly(newArr);
而不仅仅是newArr
返回月份名称。
我的问题是,changeToFriendly(newArr);
如果函数不对数组执行任何操作,只需遍历它并检查与月份名称对应的数字,newArr
如何更改。{/ p>
function makeFriendlyDates(arr) {
var newArr = [];
var elem;
for (elem in arr) {
newArr.push(arr[elem].split('-'));
}
document.getElementById('result').innerHTML = newArr;
function changeToFriendly(arr1) {
var month = '';
var elem1;
for (elem1 in arr1) {
if (arr1[elem1][1] = '01') {
month = 'January';
} else if (arr1[elem1][1] === '02') {
month = 'February';
} else if (arr1[elem1][1] === '03') {
month = 'March';
} else if (arr1[elem1][1] === '04') {
month = 'April';
} else if (arr1[elem1][1] === '05') {
month = 'May';
} else if (arr1[elem1][1] === '06') {
month = 'June';
} else if (arr1[elem1][1] === '07') {
month = 'July';
} else if (arr1[elem1][1] === '08') {
month = 'August';
} else if (arr1[elem1][1] === '09') {
month = 'September';
} else if (arr1[elem1][1] === '10') {
month = 'October';
} else if (arr1[elem1][1] === '11') {
month = 'November';
} else if (arr1[elem1][1] === '12') {
month = 'December';
}
}
document.getElementById('result1').innerHTML = newArr;
return month;
}
changeToFriendly(newArr);
}
makeFriendlyDates(['2016-07-01', '2016-08-04']);
&#13;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
</head>
<body>
<p id="result"></p>
<p id="result1"></p>
</body>
</html>
&#13;
答案 0 :(得分:5)
您的问题很可能是=
这里的问题:
for (elem1 in arr1) {
if (arr1[elem1][1] = '01') {
^^^
...这意味着您的if
总是评估为真。
答案 1 :(得分:0)
以下内容应该有效。
function makeFriendlyDates (arr) {
// Splits each element of the array, and returns an array of results
var splitArr = arr.map(function (el) {return el.split('-');});
// Prefer console.log to printing to HTML
// document.getElementById('result').innerHTML = splitArr;
console.log(splitArr);
var monthNames = ["January", "February", "March", "April",
"May", "June", "July", "August", "September", "October",
"November", "December"
];
// See http://stackoverflow.com/a/1643468/1327983
splitArr.forEach(function (el) {
var month = monthNames[ parseInt(el[1])-1 ];
// What do you want to do with it from here?
el[1] = month;
});
// Demonstrate results
console.log(splitArr);
}
makeFriendlyDates(['2016-07-01', '2016-08-04']);