Oct 17, 2020

API Testing 'A Beginners View': JavaScript shift() Method

The shift() method removes the first element from an array and returns that removed value. The shift method removes the element at the zeroeth index and shifts the values at consecutive indexes down, then returns the removed value. If the length property is zero, it returns the output as 'undefined'.


Syntax:

arr.shift()


Return value:

The removed element from the array. If the array is empty value returned is undefined.


Explanation with Example:

Response Body:












Test Script:

var resp = JSON.parse(responseBody);

//API Testing 'A Beginners View': JavaScript shift() Method
accept_encoding = [];
var split = "gzip, deflate, br";
var split_value = split.split(",");
console.log("accept-encoding is: " + split_value);
var shift_value = split_value.shift();
console.log(shift_value);
var shift_value = split_value.shift();
console.log(shift_value);
var shift_value = split_value.shift();
console.log(shift_value);
var shift_value = split_value.shift();
console.log(shift_value);
var shift_value = split_value.shift();
console.log(shift_value);

Console Output:








In the above example, I have used the previous post on 'split' method (https://softwaretestingcafebyjency.blogspot.com/2020/10/JavaScript-split-Method.html) and continued to add the shift() method to return the first element with the same example. 


The split_value.shift() method is used to return the first element from the string defined.


No comments: