简体   繁体   中英

Object doesn't support property or method 'slice'

I'm newbie to the Javascript/Jquery world. I have a div with several links and i want to collect the url's .

Then i want to extract from those href's the last 9 characters (actually i wish to optimize it and collect the digits independently the length at the end of each string).I tried to extract them with the slice() method but it does not work.

In console the error is

Object doesn't support property or method 'slice'

Can i convert the object to a string ? Your help is appreciated ! The code is the following

$(document).ready(function(){

  var $posts= $('a.entry_title').each(function(){
    $(this).attr('href');
  });

  var posts1 = $posts[0].slice(-9);
  var posts2 = $posts[1].slice(-9);

  var posts = ["MyURL"+ posts1,"MyURL"+posts2]
  $('#div1').load(posts[0] + " .shadow3");
  $('#div2').load(posts[1] + " .shadow3");

});
</script>

You see Object doesn't support because $.each returns a jQuery object.

Use .map() instead because it returns an array on which slice would work

var $posts= $('a.entry_title').map(function(){
   return $(this).attr('href');
});

Result would be

["link1", "link2", "link3"....] // just a sample

If you wish to get an array of hrefs with last nine characters of each link you can use map this way

var $posts= $('a.entry_title').map(function(){
   return $(this).attr('href').slice(-9); // or you can do your own magic
});

Result would look like this

["k1", "k2", "k3"....] // after slicing the words 

Try next one:

var hrefs = []; // list of collected and sliced hrefs.
var $posts= $('a.entry_title').each(function() {
    // slice & push each href into list.
    hrefs.push($(this).attr('href').slice(-9));
});
console.log('href list:', hrefs); // control result.
var posts = ["MyURL"+ hrefs[0],"MyURL"+hrefs[1]]

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