// 最长公共子前缀 var testStrList = ['abcd','abc','abcdmg','aggg'] function longCommon1(list){ let first = list[0] for(let i = 0;i < first.length;i++){ let str = first.charAt(i) for(let j = 1;j<list.length;j++){ if(i == list[j].length || str !== list[j].charAt(i)){ return first.substring(0, i) } } } } function longCommon(list) { if(list.length == 0){ return '' } let result = list[0] for(let i = 0; i < list.length; i++) { while(list[i].indexOf(result) != 0) { console.log('1',list[i],result) result = result.substring(0, result.length - 1); console.log('2',list[i],result) if(result.length == 0) { return ""; } } } return result; } console.log(longCommon1(testStrList))