问题
I'm trying to make all array indexes lowercase strings, but it's not working. I looked at other answers on here and tried their solutions like using toString()
before adding toLowerCase
but it doesn't work, which is weird.
I created a jsfiddle of the problem here.
JS:
$(colorArr).each(function(i, item) // loop thru each of elements in colorArr and make lowercase + trim
{
if(colorArr[i] !== undefined) // check if colorArr index undefined
{
colorArr[i].toString().toLowerCase().trim(); // FIX HERE
/* TRIED - DIDN'T WORK!
colorArr[i].toLowerCase().trim();
*/
}
});
回答1:
i updated your fiddle
https://jsfiddle.net/af91r2cq/6/
colorArr[i] = colorArr[i].toString().toLowerCase().trim(); // FIX HERE
your way was really close ;)
回答2:
You need to set the value back
It should be
colorArr[i] = colorArr[i].toString().toLowerCase().trim(); // FIX HERE
Or simply
colorArr = colorArr.map(function(value){ return value ? value.toLowerCase().trim() : ""; });
回答3:
Another way change all defined values in the array to lowercase is to use the jQuery.map
function like so:
colorArr = $.map(colorArr, function(item, i) {
if(item !== undefined) {
return item.toString().toLowerCase().trim();
}
});
来源:https://stackoverflow.com/questions/36180297/javascript-making-array-index-tolowercase-not-working