0

i have an array which contains different values, i want split them off and print in browser. but i want alert it first value. i have made a function but it is not wokring

<script type="text/javascript">
$(function(){
    var jam= new Array("first","second","third","fourth");
    var Klnew= jam.split(",");

    //for(i=0;i<Klnew.length;i++) {}

    alert(Klnew[0])     
});    
</script>
4
  • 1
    split is the function of String,not of Array. Commented Jun 14, 2012 at 6:40
  • i'm also wondering what should happen if you call split on an array :D Commented Jun 14, 2012 at 6:40
  • @sdepold. ohhh, please don't, the world will come to it's end! Commented Jun 14, 2012 at 6:43
  • @gdoron :D it could probably return an array of arrays. so every string inside the array gets split :D Commented Jun 14, 2012 at 6:46

6 Answers 6

7

You can't split an array. It is already split.

You might be looking for something like this:

var foo = ['a', 'b', 'c']; 
console.log(foo.shift());    // Outputs "a"
console.log(foo.join(','));  // Outputs "b,c"

… but it hard to tell what your goals are from your question.

Sign up to request clarification or add additional context in comments.

Comments

1
   $(function(){
        var jam= new Array("first","second","third","fourth");
        var Klnew= jam.slice();
    //  for(i=0;i<Klnew.length;i++) {}
        alert(Klnew[0])
   })

Comments

1
var jam= new Array("first","second","third","fourth");
alert(jam[0]); // alert before the join.
var Klnew= jam.join(","); // join, not split the array...

Output:

"first,second,third,fourth"

2 Comments

ok thanks but now i want split them and print using document.write
@Quentin. I meant join, sorry.
0

You would use split for getting an array out of a string:

"first,second,third,fourth".split(',') ==> ['first', 'second', 'third', 'fourth']

Comments

0

split (of string) method splits string to array.

join (of array) method joins array elements into string. So:

arr = Array("first","second","third","fourth");
str = arr.join(",")
alert(str) // will alert "first,second,third,fourth"
alert(arr == str.split(","))// will alert true

1 Comment

The second alert is false because both sides are objects and therefore must return false by definition.
0

even this is going to work--

var jam = new Array("first", "second", "third", "fourth");
alert(jam[0]);  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.