大家都知道字串是 JavaScript 的一种型别,有时候在处理资料上不免要把字串拆开
此时 split 就是一个好方法:
var weather = '今天天气是晴天';var show = weather.split('');console.log(show);
这时候在 console 看,字串就会被拆成一个字一个字且用阵列的方式传回,如下:['今','天','天','气','是','晴','天'];
而 split 对于在中文字串跟英文字串上又有一些小差别,下面举例英文字串:
var weather = 'today is sunday';var show = weather.split('');console.log(show);
这时候在 console 看,英文字串会被拆解成一个字母一个字母的:['t','o','d','a','y','','i','s','','s','u','n','d','a','y'];
若上述改成:
var weather = 'today is sunday';var show = weather.split(' ');console.log(show);
这时候在 console 看,就会被拆解成单字传回了:['today','is','suday']
所以英文字串处理上,看是要传回单字还是要传回字母,在使用 split 方法上多一个空白很重要