麻烦老师看下,这样写是否正确,是否需要改进,谢谢老师
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> let arr = ["a", "b", "c", "d", "c", "f", "e"]; // indexOf function myIndexOf(arr, keyword, index) { for (var i = 0; i < arr.length; i++) { if (index) { if (i >= index && arr[i] === keyword) { return i; } } else { if (arr[i] === keyword) { return i; } } } return -1; } console.log(myIndexOf(arr, "b")); console.log(arr.indexOf("b")); console.log(myIndexOf(arr, "c", 3)); console.log(arr.indexOf("c", 3)); // lastIndexOf function myLastIndexOf(arr, keyword, index) { let reverseArr = arr.concat(); reverseArr.reverse(); for (var i = 0; i < arr.length; i++) { if (index) { if (i >= index && reverseArr[i] === keyword) { return arr.length -1 -i; } } else { if (reverseArr[i] === keyword) { return arr.length -1 -i; } } } return -1; } console.log(myLastIndexOf(arr, "f")); console.log(arr.lastIndexOf("f")); console.log(myLastIndexOf(arr, "c", 3)); console.log(arr.lastIndexOf("c", 3)); </script> </body> </html>
0
收起
正在回答
1回答
同学这是做了两种方法吗?效果实现的是可以的,棒棒哒。
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星