Puzzling javascript behavior - javascript

I typed the following into the chrome console:
> Array.prototype.slice.call([1,2], 0)
[1, 2]
> Array.prototype.slice.call([1,2], 1)
[2]
Why does the first call not return 1?

Array.prototype.slice.call([1,2], 0) returns all elements of the array starting from index 0, and puts the whole into the array.
Array.prototype.slice.call([1,2], 1) returns all elements of the array starting from index 1, and puts the whole into the array, however this time it finds only 1 element, the 2.

Slice with one argument returns the array from the index position you give in the argument. In your case 0 marks the index position 0, so it returns the whole array.
Array.prototype.slice.call([1,2,3,4,5], 0)
//=> [1,2,3,4,5] because index to start is 0
Array.prototype.slice.call([1,2,3,4,5], 2)
//=> [3,4,5] because index to start is 2
The second argument would be how many element it slices out starting from index, so:
Array.prototype.slice.call([1,2,3,4,5], 0, 1)
//=> [1] because index to start is 0 and number of elements to slice is 1
Array.prototype.slice.call([1,2,3,4,5], 2, 2)
//=> [3,4] because index to start is 2 and number of elements to slice is 2
Find more in the documentation here

As indicated here, the slice method accepts a start and optionally an end offset, not the index of the element to slice out. If no offset is provided, it will slice to the end of the array.
In your first example, slice starts from element 0, while in the second example it starts from element 1. In both occassions it will any elements it can find at that index and after, since you have not specified an offset.

First parameter to slice is the start index in the array (counting from zero).
The second parameter (which is not given in either of your examples), is the end. Precisely it is: one past the inclusive end index. Anyway, it defaults to the end of the array, which is the behaviour you see.
Array.prototype.slice.call([1,2], 0, 1)
should give you [1]

slice.call(arguments, Fromindex);
The Fromindex means to slice the arguments list from index to the end.
as your case
slice the arguments from index 1
thats why you get [2]

Related

array.reverse() block-wise in flat array

I'm writing a pixel animation reading data from a Unit8Array holding
5 frames, 72 binaries each. Now I thought to reverse the frames to reverse animation. So my question:
Is there a way to reverse block-wise, or has anybody a creative idea, how I could do so?
(I can't just run backwards, as each frame needs the info of previous)
const myArr = [1,2,3,4,5,6,7,8];
console.log(myArr.reverse());//8,7,6,5,4,3,2,1
//how to reach [7,8,5,6,3,4,1,2]?
//would work fine with 2D array,
//but don't have 2D
const my2D = [[1,2],[3,4],[5,6],[7,8]];
This should do it:
const reversed = myArr
.map((_, i, a) => a[i ^ 1])
.reverse()
The way it works is that it maps each array element to another element with the index changed by inverting the 1 bit using XOR (for example 4^1=5, 5^1=4, 6^1=7, 7^1=6, etc.) and then reversing the whole array.
This trick can be used for any power of two: You can reverse groups of 4 elements using ^ 3 to flip the 1 and 2 bits, groups of 8 using ^ 7 to flip the 4, 2 and 1 bits and so on. (If you'd need other group sizes, you would have to use a more expensive operation like i + size - 1 - 2 * (i % size) instead.)
map calls the callback with several arguments - the first one is the value of the element but we don't need it really, so we'll assign it to an unused variable _. The second one is the index, and the third one is the array itself. Actually we only need the index, but with the third argument we can avoid writing the name of the array twice in the line (myArr.map((_, i) => myArr[i ^ 1]) would work too).
Note: depending on your exact use case maybe another option would be to do an array.length - i ^ 1 operation on the index when accessing the data, instead of creating a new array.
Inspired by CherryDT's answer, it can be done with one map call:
const arr = [1,2,3,4,5,6,7,8];
console.log(
arr.map((_, i) => arr[arr.length - i - 1 ^ 1])
);

How the output has 4 items in the array?

var arr =[1,2,3,4];
var ct = arr.length;
for( var i=0;i<ct;i++){
ct--;
arr[i]+=i;
}
console.log(arr);//1,3,3,4
Explain the code, it's confusing me.
Your loop run 2 times.
First time with i = 0, first item in array increase 0 -> 1
Second time with i= 1, second item in array increase 1 -> 3
The ct decrease so that your loop can not reach third time, array item remain keep old value.
Well, you are not really changing the size of the array.
You create an array with 4 elements (length = 4)
You record the length into an integer, this is a copy of the value
Inside the loop, you decrease the value of ct, which is a copy of the length, so it does not effect the array at all
You increase the current element of the array by what i is at the time, so for the first iteration of the loop, you do 1 + 0
So you see, no changes are made to the length of the array, only the values that the array contains.

Finding the mirror index in a palindrome + javascript

My code:
function palindrome(str) {
return str.split('').every((char, i) => {
return char === str[str.length - i - 1] ? true : false;
})
}
palindrome('abcba');
In using the debugger and console.log I get why in the comparison statement we write - i, because that gets us to the correct index on the opposite side but how would one know to do this from the very beginning?
Is there an explanation or a diagram of some sort that explains how or why - i will get you to the index of the character on the opposite side? Just finding it difficult to properly wrap my had around this one.
Any help much appreciated although I imagine this is a difficult one to explain.
Okay let's break it down.
str.split('')
This line breaks your 'abcba' string into an array. The result will be:
['a', 'b', 'c', 'b', 'a']
Now that you have an array that you can loop over and select certain indexes from the array. This is very useful in the case of a palindrome.
Because you want to know if the word is the same when it is mirrored. And you figure that out by starting at the head and tail of the array.
The first item in the array being the index of 0 [0] and the last one, well that depends on the array. But if you have the array and and subtract [array.length - 1], which in the word abcba is [5 - 1] and you end up with the last item in the array, which has the index of 4 [4].
// First iteration.
// First and last items in array.
// [0] and [array.length - 1] or [4].
↓ ↓
['a', 'b', 'c', 'b', 'a']
So in the loop you go from left to right in your array. And compare the first value with the last value. Your example uses the every method which at the end returns true if every condition in your loop has returned true, or false whenever that is not the case.
The loop also exposes a current index value. In your example called i, short for index. If you finished comparing the first and last value you want to shift over to the next item in the array to start comparing the second and first to last value. That's where the formula comes from.
str.split('').every((char, i) => {
return char === str[str.length - i - 1] ? true : false;
});
In the first iteration the value of i is 0. So you have the formula: length of the array, subtract 0 and subtract 1. Which gives you the last item.
In the second iteration i is now 1. Meaning we are in the second item of the array. If you apply i to the formula again, you can start to count back from the end of the array: length of the array, subtract 1 and subtract 1. Which adds up to 3.
// Second iteration.
// Second and first to last item in array.
// [1] and [array.length - 2] or [3].
↓ ↓
['a', 'b', 'c', 'b', 'a']
And with the next iteration you get an overlap, but not in cases with an even numbered word. But here they are both checking if c matches c.
// Third iteration.
// Third and and second to last item in array.
// [2] and [array.length - 3] or [2].
↓
↓
['a', 'b', 'c', 'b', 'a']
And this continues on until the last item in the array is reached with the loop continuing counting up, and the formula counting down.
I hope this makes sense and helps you understand it a bit more.

Array Length in Javascript

I am an absolute beginner to programming and Javascript and was watching one of Douglas crockford's videos where he says the following
Arrays unlike objects have a special length member
It is always 1 larger than the highest integer subscript
In this array
var a = [1,2,3,4,5,6,7]
a.length equals to 7.
So I am not quite sure what 1 larger than highest integer subscript means...? Is it just an outdated piece of info from a older version of Javascript or am i missing something ?
length equals to no of elements in the array and index starts from 0 , understand it like you are not starting with 1 instead with 0 so you will have 1 less than total elements(length). so
length = total elements
and
last index = length-1;
It just means that the length of an array is always* its largest index + 1.
Consider:
var a = [];
a[6] = 'foo';
console.log(a.length) //7
a[20] = 'bar';
console.log(a.length) //21
*actually not always, like for example when you use Array constructor with number argument: var a = new Array(5), the array is empty, but it has its length explicitely set to 5
Arrays are indexed from 0 (first element), but length is from 1 (one element) (array won't have length of -1 if there won't be no elements, the length would be 0; if there are 2 elements, second element will have the index of 1 and the length will be 2).
Indexes and lengths are different. While a JavaScript array will start at 0, the length will always be the true number. This is helpful since on a slice, the last number is NOT inclusive.

JavaScript, finding an array instance with indexOf() and lastIndexOf() methods

I'm reading "Professional JavaScript for Web Developers" (third edition) by Nicholas Zakas in an attempt to teach myself JS. However, I am having difficulty following the Location Methods section of chapter 5 on page 118 (in case you have the book). He explains that "the indexOf() method starts searching from the front of the array (item 0) and continues to the back, whereas lastIndexOf() starts from the last item in the array and continues to the front". Also he explains that "Each of these methods accepts two arguments: the item to look for and an optional index from which to start looking". He then attempts to illustrate this with examples.
As you can see below, to the right of the alert statements, he has listed what the correct output will be for each statement given the supplied argument(s). I do not understand how these outputs are determined. For example, how does alert(numbers.indexOf(4)); produce 3? I was reading this last night and thought I was just too tired to understand, however, I still cannot seem to figure out how this is achieved. I searched the Errata section from the book's companion website for a possible typo, but nothing was listed. I also searched elsewhere but found examples that mostly dealt with strings instead of numbers. Thanks for any help. This is my first post to stack overflow so my apologies if I have done something incorrect in my post.
His examples:
var numbers = [1,2,3,4,5,4,3,2,1];
alert(numbers.indexOf(4)); //3
alert(numbers.lastIndexOf(4)); //5
alert(numbers.indexOf(4, 4)); //5
alert(numbers.lastIndexOf(4, 4)); //3
The way I thought the outcome would be:
alert(numbers.indexOf(4));
//the item in the array with the fourth index, or 5
alert(numbers.lastIndexOf(4));
//5 (this was only one that seemed to make sense to me) by counting back from the last value
alert(numbers.indexOf(4, 4));
//start looking at index 4, or 5, and then count right four places to end up at 1 (last item in array).
alert(numbers.lastIndexOf(4, 4));
//1, counting back to the left from the value with index 4, or 5, to reach the first value in the array.
Any help in determining the outputs based on the required argument and then how to also count from a specified value given the additional optional argument would be much appreciated. Thanks again.
In most of the Programming languages, default indexing start from 0. Therefore, you have an understanding problem. Double consider your example with index starting from 0.
var numbers = [1,2,3,4,5,4,3,2,1];
alert(numbers.indexOf(4)); //3, because 4 is at 3rd index
alert(numbers.lastIndexOf(4)); //5, because last 4 is at 5th index
alert(numbers.indexOf(4, 4)); //5, because searching will start from 4th index
alert(numbers.lastIndexOf(4, 4)); //3, because searching will start from last 3rd element.
JavasScript arrays are zero indexed, in other words, the first item has an index of zero. This is true for almost all programming languages (apart fro XPath for some odd reason!).
The indexOf function returns the index of the first item it finds that equals the supplied argument.
var numbers = [1,2,3,4,5,4,3,2,1];
var index = numbers.indexOf(4); // index is 3
alert(numbers[index]); // outputs 4
In JS or many other languages the index count of array starts with 0 so for,
var numbers = [1,2,3,4,5,4,3,2,1];
numbers[0] = 1
numbers[1] = 2
numbers[2] = 3
numbers[3] = 4
numbers[4] = 5
numbers[5] = 4
numbers[6] = 3
numbers[7] = 2
numbers[8] = 1
It's
indexOf("SearchString");
not
indexOf(indexNumber);
That would be awfully redundant.

Categories