数组去重
1、indexOf
function unique(arr
) {
if (!Array
.isArray(arr
)) {
console
.log("type error!");
return;
}
var array
= [];
for (let i
= 0; i
< arr
.length
; i
++) {
if (array
.indexOf(arr
[i
]) === -1) {
array
.push(arr
[i
]);
}
}
return array
}
2、双层for循环
function unique(arr
) {
if (!Array
.isArray(arr
)) {
console
.log("type error!");
return;
}
for (let i
= 0; i
< arr
.length
; i
++) {
for (let j
= i
+ 1; j
< arr
.length
; j
++) {
if (arr
[i
] == arr
[j
]) {
arr
.splice(j
, 1);
j
--;
}
}
}
return arr
}
3、ES6 Array.from与set的使用
function unique(arr
) {
if (!Array
.isArray(arr
)) {
console
.log("type error!");
return;
}
return Array
.from(new Set(arr
));
}
字符串反转
1、for循环反转
function reverseStr(str
) {
let result
= "";
for (let i
= str
.length
- 1; i
>= 0; i
--) {
result
+= str
[i
];
}
return result
;
}
2、使用数组方法reverse()、join()
function reverseStr(str
) {
let result
= str
.split('').reverse().join('');
return result
;
}
3、JavaScript charAt() 方法
function reverseStr(str
) {
var strArr
= str
.split('');
var result
= '';
for (let i
= strArr
.length
- 1; i
>= 0; i
--) {
result
+= str
.charAt(i
);
}
return result
;
}
回文判断
1、第一种for循环
function palindRome(str
) {
if (!str
|| str
.length
< 2) {
return;
}
var len
= str
.length
;
var result
= "";
for (let i
= len
- 1; i
>= 0; i
--) {
result
+= str
[i
];
}
return result
== str
;
}
2、第二种for循环
function palindRome(str
) {
if (!str
|| str
.length
< 2) {
return;
}
for (let i
= 0; i
< str
.length
/ 2; i
++) {
if (str
[i
] !== str
[str
.length
- 1 - i
]) {
return false;
}
}
return true;
}
3、for循环+charAt()
function palindRome(str
) {
for (let i
= 0; i
< str
.length
; i
++) {
if (str
.charAt(i
) !== str
.charAt(str
.length
- 1 - i
)) {
return false
}
return true
}
}
转载请注明原文地址: https://lol.8miu.com/read-22884.html