简体   繁体   中英

Jquery slice code give error help me please

     let slice = yeni => (yeni.slice(-1)); 
     var test = slice(enler); alert(test); 
     

test How to use slice code correct? Thanks for help Lemme know if need some another code I mean how I can make it like function?

Usually if yeni variable have value 25 I can use it like that yeni.slice(-1); its output 5 yes? But its give error on console and its not work

The code provided

 let slice = yeni => (yeni.slice(-1)); 
 var test = slice(enler); 
 alert(test); 
 

will work if enler is a string, otherwise gives .slice is not a function error.

To get this to work with a number as well as a string, the number needs to be converted to a string before the [system].slice method is called. There are many ways to do this, one is to concatenate with an empty string which will coerce the number to a string, ie:

let s = i + "";

Adding this to the function gives:

let myslice = arg => (arg+"").slice(-1);

Sample:

 let slice = yeni => yeni.slice(-1); console.log(slice("25")) try { console.log(slice(25)) } catch { console.log("FAILED") } let slice2 = yeni => (yeni + "").slice(-1); console.log(slice2("25")) try { console.log(slice2(25)) } catch { console.log("FAILED") }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM