Javascript - Making Array Index toLowerCase() not working

余生长醉 提交于 2019-12-31 04:00:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!