รหัสนี้ใช้ไม่ได้ใน Internet Explorer ทางเลือกอื่น?
"abcde".includes("cd")
รหัสนี้ใช้ไม่ได้ใน Internet Explorer ทางเลือกอื่น?
"abcde".includes("cd")
คำตอบ:
String.prototype.includes
คือตามที่คุณเขียนไม่รองรับใน Internet Explorer (หรือ Opera)
String.prototype.indexOf
แต่คุณสามารถใช้ #indexOf
ผลตอบแทนดัชนีของตัวอักษรตัวแรกของ substring -1
ถ้ามันอยู่ในสตริงมิฉะนั้นผลตอบแทน (เหมือน Array เทียบเท่า)
var myString = 'this is my string';
myString.indexOf('string');
// -> 11
myString.indexOf('hello');
// -> -1
MDN มี polyfill สำหรับincludes
ใช้indexOf
: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Polyfill
แก้ไข: Opera สนับสนุนincludes
เป็นของรุ่น 28
แก้ไข 2: Edge เวอร์ชันปัจจุบันรองรับวิธีนี้ (ข้อมูล ณ ปี 2019)
Boolean
เราสามารถทำได้(myString.indexOf('string') > -1) // to get a boolean true or false
หรือใส่ลงในไฟล์ Javascript แล้วขอให้มีความสุข :)
String.prototype.includes = function (str) {
var returnValue = false;
if (this.indexOf(str) !== -1) {
returnValue = true;
}
return returnValue;
}
for...in
มันจะวนซ้ำString.prototype.includes
หากมีการกำหนดไว้เช่นนี้
return this.indexOf(str) !== -1;
รวมถึง () ไม่รองรับเบราว์เซอร์ส่วนใหญ่ ตัวเลือกของคุณสามารถใช้ได้
-polyfill จาก MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes
หรือใช้
-indexof ()
var str = "abcde";
var n = str.indexOf("cd");
ซึ่งทำให้คุณได้ n = 2
สิ่งนี้ได้รับการสนับสนุนอย่างกว้างขวาง
for...in
! มันจะวนซ้ำString.prototype.includes
ถ้าคุณกำหนดแบบนั้น
ปัญหา:
ลองเรียกใช้ด้านล่าง (โดยไม่มีโซลูชัน) จาก Internet Explorerและดูผลลัพธ์
console.log("abcde".includes("cd"));
วิธีการแก้:
ตอนนี้เรียกใช้โซลูชันด้านล่างและตรวจสอบผลลัพธ์
if (!String.prototype.includes) {//To check browser supports or not
String.prototype.includes = function (str) {//If not supported, then define the method
return this.indexOf(str) !== -1;
}
}
console.log("abcde".includes("cd"));
ฉันมีปัญหาเดียวกันเมื่อทำงานใน Angular 5 เพื่อให้ทำงานได้โดยตรงโดยไม่ต้องเขียน polyfill ด้วยตัวเองเพียงเพิ่มบรรทัดต่อไปนี้ในไฟล์ polyfills.ts:
import "core-js/es7/array"
นอกจากนี้tsconfig.json
ส่วน lib อาจเกี่ยวข้อง:
"lib": [
"es2017",
"dom"
],
สำหรับการตอบสนอง:
import 'react-app-polyfill/ie11';
import 'core-js/es5';
import 'core-js/es6';
import 'core-js/es7';
การแก้ไขปัญหาสำหรับ - รวม () ค้นหา () และอื่น ๆ ..
หากคุณต้องการใช้Array.prototype.include()
ในจาวาสคริปต์ต่อไปคุณสามารถใช้สคริปต์นี้:
github-script-ie-include
ที่จะแปลงฟังก์ชัน include () เป็น match () โดยอัตโนมัติหากตรวจพบ IE
ตัวเลือกอื่นใช้เสมอstring.match(Regex(expression))
มันใช้ได้กับฉัน:
function stringIncludes(a, b) {
return a.indexOf(b) !== -1;
}
ก็ทำได้เหมือนกัน !! และ ~ ตัวดำเนินการ
var myString = 'this is my string';
!!~myString.indexOf('string');
// -> true
!!~myString.indexOf('hello');
// -> false
นี่คือคำอธิบายของตัวดำเนินการทั้งสอง (!! และ ~)
อะไรคือ !! (ไม่ใช่) ตัวดำเนินการใน JavaScript?
https://www.joezimjs.com/javascript/great-mystery-of-the-tilde/