官方的
var lengthOfLastWord = function(s) {
let index = s.length - 1;
while (s[index] === ' ') {
index--;
}
let wordLength = 0;
while (index >= 0 && s[index] !== ' ') {
wordLength++;
index--;
}
return wordLength;
};
我的
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
let arr =s.split(' ');
element= ''
arr = arr.filter(item => item != element)
return arr[arr.length-1].length
};
split
split() 通过搜索模式将字符串分割成一个有序的子串列表,将这些子串放入一个数组,并返回该数组。
const str = 'The quick brown fox jumps over the lazy dog.';
const words = str.split(' ');
console.log(words[3]);
// Expected output: "fox"
const chars = str.split('');
console.log(chars[8]);
// Expected output: "k"
const strCopy = str.split();
console.log(strCopy);
// Expected output: Array ["The quick brown fox jumps over the lazy dog."]
筛选数组中不想要的元素
element= ''
arr = arr.filter(item => item != element)