javascript - filter(String) also return number -
javascript - filter(String) also return number -
can explain me why filter(string) homecoming number?
class="snippet-code-js lang-js prettyprint-override">var arr = [1, "a", '7'], numarr = arr.filter(number), // homecoming 1, 7 (it's ok) strarr = arr.filter(string); // why homecoming 1, a, 7 alert("numarr = " + numarr + "\n" + "strarr = " + strarr); alert("typeof arr[0] = " + typeof arr[0]);
in illustration above, typeof arr[0] number; why it's not filtered instrarr?
thanks.
the .filter() api passes each array element value function provide. value returned function coerced boolean , tested. true results included in returned array .filter().
the number constructor interprets argument number, , returns value. when passed string "a" .filter() mechanism, returns nan, interpreted false.
the string constructor performs similar operation, key difference makes valid string. thus, number 1 in array returned "1", when converted boolean true because it's non-empty string.
to state way, not case number , string constructors perform sort of yes/no identification of numeric or string values, can't utilize them filter values in array type.
javascript
Comments
Post a Comment