OrgPad logo

javascript

Created by Jiří Kofránek

javascript

Vytváření NOVÉHO pole, prvku, indexu či logické hodnoty ZE STARÉHO POLE, které se NEZMĚNÍ

Obrácení pořadí prvků pole.reverse()

/**********************************************************************
reverse()
Return value
The reversed array.
**********************************************************************/
const arrayOrig = ['one', 'two', 'three']
console.log('arrayA:', arrayOrig)
// expected output: "arrayOrig:" Array ["one", "two", "three"]
const reversed = arrayOrig.reverse()
console.log('reversed = arrayOrig.reverse()')
console.log('reversed:', reversed)
// expected output: "reversed:" Array ["three", "two", "one"]
// Careful: reverse is destructive -- it changes the original array.
console.log('Careful: reverse is destructive --it changes the original array.')
console.log('arrayOrig:', arrayOrig)
// expected output: "arrayOrog:" Array ["three", "two", "one"]

image

findIndex

//vrátí první prvek, který vyhovuje podmínkám
//index = array.findIndex((el,i,arr)=>{...})
const arrayT = [5, 12, 8, 130, 44]
const isLargeNumber = element => element > 13
console.log('in:',arrayT,'index of (element>13):',arrayT.findIndex(isLargeNumber))
// expected output: 130

filter

Metoda filter()vytvoří mělkou kopii části daného pole,  tvořenou prvky z daného pole, které projdou testem zadané funkce.

//array.filter(element, index,array)=>{...}
testArr = [400, 500, 600, 2000, 500, 350] const filteredArr = testArr.filter((el, i, arr) => {
return el >= 500 && el <= 1000
}) //[500,600,500]
console.log('testedArr=', testedArr)
console.log('updatedArr=', filteredArr)

some

Vrátí hodnotu true, pokud alespoň jeden prvek v poli vyhovuje zadané testovací funkci.

console.log('testArr.some((el, i, arr) => {...})')
testArr = [400, 500, 600, 2000, 500, 350]
const someMore1000Element = testArr.some((el, i, arr) => { return el > 1000})
console.log('someMore1000Element=', someMore1000Element) //true

find

//found = arrray.find((el,i,arr)=>{...})
//vrátí pole, které vyhovuje podmínkám
const arraySearch = [5, 12, 8, 130, 44]
const found = arraySearch.find(element => element > 10)
console.log('in:',arraySearch,'element > 10:',found)
// expected output: 12

reduce

Metoda reduce()instancí Arrayprovede uživatelem dodanou funkci zpětného volání "reduktor" na každém prvku pole v pořadí a předá návratovou hodnotu z výpočtu na předchozí prvek. Konečným výsledkem spuštění reduktoru napříč všemi prvky pole je jedna hodnota.

Při prvním spuštění zpětného volání neexistuje žádná "návratová hodnota předchozího výpočtu". Pokud je dodán, může být místo něj použita počáteční hodnota. Jinak je prvek pole na indexu 0 použit jako počáteční hodnota a iterace začíná od dalšího prvku (index 1 místo indexu 0).

const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue,
);
console.log(sumWithInitial);
// Expected output: 10
//reduce((accumulator, currentValue) => { ... } )
//reduce((accumulator, currentValue, index) => { ... } )
//reduce((accumulator, currentValue, index, array) => { ... } )
//reduce((accumulator, currentValue, index, array) => { ... }, initialValue)
//vytvoří prvek z pole podle zadaného algoritmu
testArr = [400, 500, 600, 2000, 500, 350]
console.log('testArr.reduce((acc, el, index, array) => {acc + el}, 0)')
const sumOfArray = testArr.reduce((acc, el, index, array) => acc + el, 0)
console.log('sumOfArray=', sumOfArray)
const averageOfArray = testArr.reduce((acc, el, index, arr) => {
console.log(
'acc=', acc,
'el=', el,
'index=', index,
'arr.length=', arr.length
)
if (index === arr.length - 1) {
return (acc + el) / arr.length
} else {
return acc + el
}},
0)
console.log('averageOfArray=', averageOfArray)

every

Vrátí hodnotu true, pokud všechny prvky v poli vyhovují zadané testovací funkci.

testArr = [400, 500, 600, 2000, 500, 350]
const everyMore500Element = testArr.every((el, i, arr) => { return el > 1000})
console.log('everyMore500Element=', everyMore500Element) //false

Karty - úkol 2

ÚKOL 2

každá karta je reprezentována objektem s následujícími poli

src:String - obsahuje adresu obrázku lícové strany karty

,rubSrc:String - obsahuje adresu obrázku na rubové straně karty

hodnota:Number - obsahuje číselnou hodnotu karty v karetní hře

např konstanta h2, reprezentuje srdcovou dvojku zapsanou jako objekt:

const h2 = { 
src: 'images/2_of_hearts.svg.png',
rubSrc: 'images/reverse.png',
hodnota: 2, rub: false
}

vaším úkolem bude k těmto polím přidat nové pole name typu String, které bude obsahovat název karty:

'c2','c3'...'c10','cj, 'cq', 'ck', 'ca' pro křížové karty,

'd2','d3'...'d10','dj, 'dq', 'dk', 'da' pro kárové karty,'

s2','s3'...'s10','sj, 'sq', 'sk', 'sa' pro pikové karty,

'h2','h3'...'h10','hj, 'hq', 'hk', 'ca' pro srdcové karty,

takže např objekt h2, reprezentující srdcovou dvojku bude vypadat takto:

const h2 = {
name: 'h2',
src: 'images/2_of_hearts.svg.png',
rubSrc: 'images/reverse.png',
hodnota: 2, rub: false
}

Bootstrap aneb je to sice rychlejší, ale zato lepší výsledek

zdrojové kódy

https://onedrive.live.com/?authkey=%21AFkDBSPhMTaHa40&id=AC047FF8728BED87%211333636&cid=AC047FF8728BED87&parId=root&parQt=sharedby&o=OneUp

Český úvod do javascriptu

zdroják:

https://onedrive.live.com/?authkey=%21AAHb2XsnIDrad6o&id=AC047FF8728BED87%211333689&cid=AC047FF8728BED87&parId=root&parQt=sharedby&o=OneUp

random from min to max

function randomIntFromInterval(min, max) 
{
// min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
//random from 1 to 6
const rndInt = randomIntFromInterval(1, 6)
console.log(rndInt)

Karty - úkol 1

zatím máme pole karet kříží (tref) - anglicky clubs

const clubs = [c2,c3,c4,c5,c6,c7,c8,c9,c10,cj,cq,ck,ca]

vytvořte a otestujte zobrazení srdcových (hearts) ,

kárových (diamonds) a pikových (spades) karet

Karty dejte do polí hearts, diamonds, a spades:

const hearts = [h2,h3,h4,h5,h6,h7,h8,h9,h10,hj,hq,hk,ha]
const diamonds =[d2,d3,d4,d5,d6,d7,d8,d9,d10,dj,dq,dk,da]
const spades = [s2,s3,s4,s5,s6,s7,s8,s9,s10,sj,sq,sk,sa]

otestujte, zda se dobře zobrazují pomocí funkce zobrazKartu(karta)

odkaz na github: https://github.com/kofranek/hraci_karty

Učebnice jazyka Javascript (anglicky)

Kapitola pole

Celá učebnice

CSS čili kaskádové styly a responzivní layout

HTML jako nezbytný úvod do webového vývoje

orgpad podpora:

Vytvoření pole

Spojování polí

Deklarace pole

Existují dvě syntaxe pro vytvoření prázdného pole:

let arr = new Array(); //vytvoří se prázdné pole arr
let arr = []; //vytvoří se prázdné pole arr

Většinou se používá druhá syntaxe s použitím hranatých závorek.

Podle druhé syntaxe můžeme zadat počáteční prvky v závorkách:

let fruits = ["Apple", "Orange", "Plum"];

 
let fruits = ["Apple", "Orange", "Plum"];alert( fruits ); // Apple,Orange,Plum

Pole může ukládat prvky libovolného typu.

Například:

 
// mix of valueslet arr = [ 'Apple', { name: 'John' }, true, function() { alert('hello'); } ];// get the object at index 1 and then show its namealert( arr[1].name ); // John// get the function at index 3 and run it arr[3](); // hello
 
Koncová čárka
Pole, stejně jako objekt, může končit čárkou:
let fruits = ["Apple","Orange","Plum",];
Styl „koncová čárka“ usnadňuje vkládání/odebírání položek,  protože všechny řádky jsou stejné.
 
 
 
Vytvoření pole pomocí new  Array()
Pole můžeme vytvářet i podle první syntaxe jako objekt s využitím konstruktoru new:
let arr = new Array("Apple", "Pear", "etc");

Používá se zřídka, protože hranaté závorky [] jsou kratší. 

Je to ale také záludná funkce.

Pokud new Arrayje voláno s jedním argumentem, kterým je číslo, pak vytvoří pole bez položek, ale s danou délkou .

Podívejme se, jak se člověk může střelit do nohy:

 
let arr = new Array(2); // will it create an array of [2] ?alert( arr[0] ); // undefined! no elements.alert( arr.length ); // length 2

Abychom se vyhnuli takovým překvapením, obvykle používáme hranaté závorky, pokud opravdu nevíme, co děláme.

 

Vícerotměrná pole

Pole mohou mít položky, které jsou také pole. Můžeme jej použít pro vícerozměrná pole, například pro ukládání matic:

 
let matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
alert( matrix[1][1] ); // 5,

[...pole1, ...pole2, ...pole3]

/************************************************** *

Spread syntax can be used when all elements from an object or array need to be included in a list of some kind.In the above example, the defined function takes x, y, and z as arguments and returns the sum of these values. An array value is also defined.When we invoke the function, we pass it all the values in the array using the spread syntax and the array name — ...numbers.If the array contained more than three numbers, e.g. [1, 2, 3, 4], then it would still work fine, except that all four would be passed, but only  the first three would be used unless you added more arguments to the function,  e.g.:

***********************************************************************************/

function sum (x, y, z, n)

{  return x + y + z + n}

/*********************************************

The above example is somewhat rigid; the real value in spread syntax is that it works with the same value, no matter how many elements are contained in the object, array, etc.It is commonly used when you want to add a new item to a local data store, or display all stored items plus a new addition. A very simple version of this kind of action could look like so:

*********************************************************/

let numberStore = [0, 1, 2]

let newNumber = 12

numberStore = [...numberStore, newNumber]

/***   SPREAD SYNTAX IN ARRAY CONCATENATION    **************************/

let arr1 = [0, 1, 2]

let arr2 = [3, 4, 5]

arr1 = [...arr2, ...arr1]

//  arr1 is now [3, 4, 5, 0, 1, 2]

navazování polí: pole.concat(pole1,pole2...)

/*******************************************************************

c

concat() concat(value0)

concat(value0, value1)

concat(value0, value1, ... , valueN)

valueN Optional

Arrays and/or values to concatenate into a new array.

If all valueN parameters are omitted, concat returns a shallow

copy of the existing array on which it is called.

Return value

A new Array instance.

The concat method creates a new array consisting of the elements in the object

on which it is called, followed in order by, for each argument, the elements

of that argument (if the argument is an array) or the argument itself

(if the argument is not an array). It does not recurse into nested array arguments.

The concat method does not alter this or any of the arrays provided as

arguments but instead returns a shallow copy that contains copies of the

same elements combined from the original arrays. Elements of the original

arrays are copied into the new array as follows:

- Object references (and not the actual object): concat copies object references

into the new array. Both the original and new array refer to the same object.

That is, if a referenced object is modified, the changes are visible to both

the new and original arrays. This includes elements of array arguments that are also arrays.

- Data types such as strings, numbers and booleans (not String, Number, and Boolean objects): concat copies the values of strings and numbers into the new array.

********************************************************************/

c

onst array10 = ['a', 'b', 'c']
const array20 = ['d', 'e', 'f']
console.log('array10=', array10)
console.log('array20=', array20)
const array30 = array10.concat(array20)
console.log('array30 = array10.concat(array20)')
console.log('array[30]=', array30)
// expected output: Array ["a", "b", "c", "d", "e", "f"]
//array 30 changedarray30.splice(0, 2, 'x', 'y')
//array10 unchanged
console.log('array30 changed=', array30)
console.log('array10 unchanged=', array10)
//********Concatenating nested arrays**************
console.log('Concatenating nested arrays')
const num1 = [[1]]const num2 = [2, [3]]
console.log('num1=', num1)
console.log('num2=', num2)
const numbers = num1.concat(num2)
console.log('numbers = num1.concat(num2)')
console.log('numbers=', numbers)
// results in [[1], 2, [3]]
// modify the first element of num1
console.log('modify the first element of num1: num1[0].push(4)')num1[0].push(4)
console.log('num1=', num1)
console.log('numbers=', numbers)
// results in [[1, 4], 2, [3]]

Zjištění délky pole

Celkový počet prvků v poli jeho vlastnost length

let fruits = ["Apple", "Orange", "Plum"];alert( fruits.length ); // 3

Můžeme také použít alert k zobrazení celého pole.

Pole jako objekt

Pole je zvláštní druh objektu. 

Hranaté závorky používané pro přístup k vlastnosti arr[0] ve skutečnosti pocházejí ze syntaxe objektu. To je v podstatě stejné jako obj[key], kde arr je objekt, zatímco čísla se používají jako klíče.

Rozšiřují objekty poskytující speciální metody pro práci s uspořádanými kolekcemi dat a také s vlastností length. Ale v jádru je to stále objekt.

Pamatujte, že v JavaScriptu existuje pouze osm základních datových typů (Number, Bigint, String, Boolean, null , undefined,  Object, Symbol).

Pole je objekt, a proto se chová jako objekt.

Například je zkopírován odkazem:

 
let fruits = ["Banana"]
let arr = fruits; // copy by reference (two variables reference the same array)
alert( arr === fruits ); // true
arr.push("Pear"); // modify the array by reference
alert( fruits ); // Banana, Pear - 2 items now

…Ale to, co dělá pole opravdu výjimečnými, je jejich vnitřní reprezentace. 

Interpret jazyka Javascript se snaží ukládat své prvky do souvislé oblasti paměti, jeden po druhém, což urychluje operace s polem.

Ale všechny optimalizace se rozbijí, pokud přestaneme pracovat s polem jako s „uspořádanou kolekcí“ a začneme s ním pracovat, jako by to byl běžný objekt.

Technicky můžeme například udělat toto:

let fruits = []; // make an array  
fruits[99999] = 5; // assign a property with the index far greater than its length
fruits.age = 25; // create a property with an arbitrary name

To je možné, protože pole jsou objekty ve své podstatě. Můžeme proto k nim přidat libovolné vlastnosti.

Ale interpret javascriptu uvidí, že pracujeme s polem jako s běžným objektem. Optimalizace specifické pro pole nejsou pro takové případy vhodné a budou vypnuty, jejich výhody zmizí.

Způsoby zneužití pole:

Představte si prosím pole jako speciální struktury pro práci s uspořádanými daty . Poskytují k tomu speciální metody. Pole jsou uvnitř JavaScriptových inrerpretů pečlivě vyladěna pro práci se souvislými uspořádanými daty, používejte je prosím tímto způsobem.

A pokud potřebujete libovolné klíče, je vysoká pravděpodobnost, že skutečně potřebujete běžný objekt {}.

 

Indexování prvků pole

Prvky pole jsou očíslovány, počínaje nulou.

Prvek můžeme získat jeho číslem (indexem) v hranatých závorkách:

let fruits = ["Apple", "Orange", "Plum"];alert( fruits[0] ); //Applealert( fruits[1] ); // Orangealert( fruits[2] ); // Plum

Když zadáme index mimo rozsah - dostaneme undefined:

alert(fruits[5]); // undefined

Můžeme nahradit prvek:
fruits[2] = 'Pear'; // now ["Apple", "Orange", "Pear"]
…Nebo přidejte do pole nový:
fruits[3] = 'Lemon'; // now ["Apple", "Orange", "Pear", "Lemon"]
 Když přidáme prvek s indexem delším než je poslední prvek, vynechané prvky budou nahrazeny hodnotou undefined
fruits[6] = 'Last'; alert(fruits)// ["Apple", "Orange", "Pear", "Lemon",,,'Last']alert( fruits[3] ); //Lemonalert( fruits[4] ); // undefinedalert( fruits[5] ); // undefinedalert( fruits[6] ); // Last

Kopírování polí

plnění polí

Array - copy Array

/******** Array - copyArray?***************/

const arrSource=[1,2,3,4]

const arrShallowCopy=arrSourceconst

arrDeepCopy=[]

arrSource.forEach((el,i)=>arrDeepCopy[i]=el)

arrDeepCopy[0]='new element shallow'

arrShallowCopy[0]='new element deep'

console.log('arrShalloCopy=',arrShallowCopy)

console.log('arrDeepCopy=',arrDeepCopy)

array.fill(value,fromIndex=0,toIndex=array.length)

const arrayFill = [1, 2, 3, 4]

console.log('before fill=',arrayFill)

// fill with 0 from position 2 until position 4

console.log('arrayFill.fill(0, 2, 4)=',arrayFill.fill(0, 2, 4))

// expected output: [1, 2, 0, 0]

// fill with 5 from position 1

console.log('arrayFill.fill(5, 1)=',arrayFill.fill(5, 1))

// expected output: [1, 5, 5, 5]

console.log('arrayFill.fill(6)=',arrayFill.fill(6))

// expected output: [6, 6, 6, 6]

map

Metoda map()vytvoří nové pole naplněné výsledky volání  funkce pro každý prvek.

// array.map((element, index, array) =>{...})
const testArr=[1,2,3,4]
const updatedArr = testArr.map((el, i, arr) => {
return el *2
})
console.log('testArr=',testArr) //[1,2,3,4]
console.log('updatedArr=', updatedArr) //[2,4,6,8]

...

V JavaScriptu mají tři tečky (...) dva hlavní významy v závislosti na kontextu, ve kterém jsou použity:

1. Rest Parameter (Zbytkový parametr): Používá se v definici funkce k seskupení zbývajících argumentů funkce do jednoho pole. To je užitečné, když nevíte, kolik argumentů bude funkci předáno.

Příklad:

function soucet(...cisla)
{ let celkem = 0; for (let cislo of cisla)
{ celkem += cislo; }
return celkem;}
console.log(soucet(1, 2, 3)); // Vypíše: 6
console.log(soucet(10, 20, 30, 40)); // Vypíše: 100
console.log(soucet()); // Vypíše: 0

2. Spread Syntax (Operátor rozšíření): Používá se k "rozbalení" prvků iterovatelných objektů (jako jsou pole, řetězce) na místech, kde se očekává nula nebo více argumentů (pro volání funkcí) nebo prvků (pro literály polí a objektů).

Příklad s poli:

const ovoce = ['jablko', 'banán']
const zelenina = ['mrkev', 'brokolice'];
// Kopírování pole
const kopieOvoce = [...ovoce];
console.log(kopieOvoce); // ['jablko', 'banán']
// Spojování polí
const jidlo = [...ovoce, ...zelenina, 'brambora'];
console.log(jidlo); // ['jablko', 'banán', 'mrkev', 'brokolice', 'brambora']
// Předávání prvků jako argumenty
function vypisOvoce(prvni, druhy) {
console.log(`První: ${prvni}, Druhý: ${druhy}`);
}
vypisOvoce(...ovoce); // Vypíše: První: jablko, Druhý: banán

Příklad s objekty:

const
osoba = { jmeno: 'Eva', vek: 30 };
const adresa = { mesto: 'Praha', ulice: 'Hlavní' };
// Kopírování objektu
const kopieOsoby = { ...osoba };
console.log(kopieOsoby); // { jmeno: 'Eva', vek: 30 }
// Slučování objektů
const osobaSAdresou = { ...osoba, ...adresa, email: 'eva@example.com' };
console.log(osobaSAdresou);
// { jmeno: 'Eva', vek: 30, mesto: 'Praha', ulice: 'Hlavní', email: 'eva@example.com' }
const aktualizaceVeku = { ...osoba, vek: 31 };
console.log(aktualizaceVeku); // { jmeno: 'Eva', vek: 31 }
const slovo = "Ahoj";
const pismena = [...slovo];
console.log(pismena); // ['A', 'h', 'o', 'j']

Stručně řečeno, tři tečky (...) jsou velmi mocným a flexibilním nástrojem v moderním JavaScriptu, který umožňuje psát čistší a expresivnější kód při práci s funkcemi, poli a objekty.

Přidávání

Ubírání

Procházení po prvcích v poli

array.push(el) ~pustˇ za poslední prvek

//přidává jeden nebo více prvků na konec

const animals = ['pigs', 'goats', 'sheep']

const count = animals.push('cows')

console.log(count)

// expected output: 4

array.unshift(el) - přidej na začátek

const arrayX = [1, 2, 3]

console.log(arrayX.unshift(4, 5))

// expected output: 5

array.shift() - odeber první prvek

const array1 = [1, 2, 3]

const firstElement = array1.shift()

console.log(array1)

// expected output: Array [2, 3]

console.log(firstElement)

// expected output: 1

array.pop() ~ popadni poslední prvek

const plants = ['a', 'b', 'c', 'd', 'e']

console.log(plants.pop())

// expected output: "e"

console.log(plants)

// expected output: Array ['a', 'b', 'c', 'd']

 

for (let i; i<array.length; i++)

const array=Array(10)

array10.fill(10)

console.log('for (let i=0; i<array.length; i++):')

for (let i = 0; i < array10.length; i++) {           console.log('array[', i, ']=', array10[i])

}

array.forEach()

const arrayABCD=['a','b','c','d']

arrayABCD.forEach((el,index,array)=>{

console.log('prvek=',el, 's indexem=',index,'v poli=',array)

})

for (el of array)

const arrayABCD=['a','b','c','d']

for (const el of arrayABCD) {

     console.log('el=', el)

}

ZMĚNA POLE

Hledání v poli

Setřídění pole pole.sort((a,b)=>a-b) nebo pole.sort(a,b)=>b-a)

testArr = [400, 500, 600, 2000, 500, 350]

console.log('****** sort *********')

console.log('testArr=', testArr)

//if > swap a<=>b

//if = ok

//if < ok

//rostoucí

let pole=[100,800,30,20.,10,300,400,900,600]

console.log(pole) // [100, 800, 30, 20, 10, 300, 400, 900, 600]

pole.sort((a,b)=>a-b)

console.log(pole) // [10, 20, 30, 100, 300, 400, 600, 800, 900]

//klesající

let pole=[100,800,30,20.,10,300,400,900,600]

console.log(pole) // [100, 800, 30, 20, 10, 300, 400, 900, 600]

pole.sort((a,b)=>b-a)

console.log(pole) //[900, 800, 600, 400, 300, 100, 30, 20, 10]

image

Vyřezávání pole pole.slice(odIndexu,doIndexu)

/*********************************************

slice(start, end)start (optional)

    Zero-based index at which to start extraction.

    A negative index can be used, indicating an offset from the end of the sequence,

    slice(-2) extracts the last two elements in the sequence.

    If start is undefined, slice starts from the index 0.

    If start is greater than the index range of the sequence,

    an empty array is returned.end (optional)

    Zero-based index before which to end extraction, slice extracts up to

    but not including end. For example, slice(1,4) extracts the second

    element through the fourth element (elements indexed 1, 2, and 3).

    A negative index can be used, indicating an offset from the end of the sequence,

    slice(2,-1) extracts the third element through the second-to-last element

    in the sequence.

    If end is omitted, slice extracts through the end of the sequence (arr.length). 

  If end is greater than the length of the sequence,

    slice extracts through to the end of the sequence (arr.length).Return value

    A new array containing the extracted elements.

*******************************************************************/

let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']

let citrus = fruits.slice(1, 3)

console.log('fruits=', fruits)

console.log('citrus = fruits.slice(1, 3)')

console.log('fruits=', fruits)

console.log('citrus=', citrus)

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']

// citrus contains ['Orange','Lemon']

image

Hledání indexu prvku v poli pole.indexOf(hledanýPrvek,odIndexu,doIndexu)

/*********************************************************************** indexOf(searchElement, fromIndex=0)SearchElement

    Element to locate in the array.fromIndex (Optional)

 

    The index to start the search at. 

    If the index is greater than or equal to the array's length, -1 is returned,

    which means the array will not be searched.

    If the provided index value is a negative number, it is taken as the offset

    from the end of the array.

    Note: if the provided index is negative, the array is still searched from front

    to back. If the provided index is 0, then the whole array will be searched.

    Default: 0 (entire array is searched).Return value

    The first index of the element in the array; -1 if not found.

****************************************************************************/

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']

console.log("beasts = ['ant', 'bison', 'camel', 'duck', 'bison']")

console.log("beasts.indexOf('bison')=", beasts.indexOf('bison'))

// expected output: 1

// start from index 2

console.log("beasts.indexOf('bison', 2)=", beasts.indexOf('bison', 2))

// expected output: 4

console.log("beasts.indexOf('giraffe')=", beasts.indexOf('giraffe'))

// expected output: -1

Pole <=>String

Testování přítomnosti prvku v poli pole.includes(prvek)

/*****************************************************************

includes(searchElement, fromIndex=0)searchElement

The value to search for fromIndex (Optional)

The position in this array at which to begin searching for searchElement.

The first element to be searched is found at fromIndex for positive values of

fromIndex, or at arr.length + fromIndex for negative values of fromIndex

(using the absolute value of fromIndex as the number of elements from the

end of the array at which to start the search).

Defaults to 0.Return value

A Boolean which is true if the value searchElement is found within the array

(or the part of the array indicated by the index fromIndex, if specified).

*****************************************************************************/

const arrayN = [1, 2, 3]
console.log('array1=', arrayN)
console.log('arrayN.includes(2)', arrayN.includes(2))
// expected output: true

Splétání pole pole.splice(odIndexu,početOdebraných,prvek1,prvek2,prvekN)

/********************************************************

splice(start, deleteCount, item1, item2, itemN)

start - The index at which to start changing the array.

deleteCount (optional) - An integer indicating the number of elements in the array 

                    to remove from start.

item1, item2, ... (optional) - The elements to add to the array, beginning from start

                     If you do not specify any elements, splice() will only remove

                    elements from the array.

Return value - An array containing the deleted elements.

               If no elements are removed, an empty array is returned.

***************************************************************/

let myAutos = ['Skoda', 'BMW', 'Volkswagen', 'Toyota']

console.log('MyAutos=', myAutos)

let removed = myAutos.splice(2, 0, 'Renault')

console.log('removed' = myAutos.splice(2, 0, 'Renault')`)

console.log('MyAutos=', myAutos)

// myAutos is ["Skoda", "BMW", "Renault", "Volkswagen", "Toyota"]

// removed is [], no elements removed

image

image

Převod pole na string pole.join('separátor')

/************************************************************

join()

join(separator=',')

(array ->string)separator (Optional)

    Specifies a string to separate each pair of adjacent elements of the array.

    The separator is converted to a string if necessary. If omitted, the array

    elements are separated with a comma (",").

    If separator is an empty string, all elements are joined without any characters

    in between them.

Return value

    A string with all array elements joined. If arr.length is 0,

    the empty string is returned.

    (reverse string->array operation - split(separator=''))

************************************************************/

var a = ['Wind', 'Water', 'Fire']

console.log('a=', a)

a.join()

//expected output: 'Wind,Water,Fire'

console.log('a.join()=', a.join())

a.join(', ')

// expected output: 'Wind, Water, Fire'

console.log("a.join(', ')=", a.join(', '))

a.join(' + ')

// expected output: 'Wind + Water + Fire'

console.log("a.join(' + ')", a.join(' + '))

a.join('')

// expected output: 'WindWaterFire'

console.log("a.join('')=", a.join(''))

Rozštěpení stringu na pole stringů string.split('separátor')

/************************************************************

split()

split(separator=',')

split(separatot=',',limit)

(string -> array)

separator Optional

    The pattern describing where each split should occur.

     The separator can be a simple string or it can be a regular expression.

   The simplest case is when separator is just a single character;

    this is used to split a delimited string.

 For example, a string containing tab

    separated values (TSV) could be parsed by passing a tab character as the separator,

    like this: myString.split("\t"). 

  If separator contains multiple characters, that entire character sequence

    must be found in order to split. 

  If separator is omitted or does not occur in str, the returned array contains 

    one element consisting of the entire string.

    If separator appears at the beginning (or end) of the string, it still has

    the effect of splitting. The result is an empty (i.e. zero length) string,

    which appears at the first (or last) position of the returned array.

    If separator is an empty string (""), str is converted to an array of each of its

    UTF-16 "characters".limit Optional

    A non-negative integer specifying a limit on the number of substrings to be

    included in the array. If provided, splits the string at each occurrence

    of the specified separator, but stops when limit entries have been placed

    in the array. Any leftover text is not included in the array at all. 

  The array may contain fewer entries than limit if the end of the string is

    reached before the limit is reached.

    If limit is 0, [] is returned.Return value

    An Array of strings, split at each point where the separator occurs in the given

    string.    ******************************************************************************/

const str = 'The quick brown fox jumps over the lazy dog.'

console.log('str=', str)

const words = str.split(' ')

console.log("words = str.split(' ')=", words)

//expected output: words = str.split(' ')= Array(9) (['The', 'quick', 'brown',...'dog.'])

console.log('words[3]=', words[3]) 

// expected output: "fox"

const chars = str.split('')

//expected output: chars = str.split('')= Array(44)  (['T','h','e',' ','q'...'d','o','g','.'])

console.log("chars = str.split('')=", chars)

console.log('chars[8]=', chars[8])

// expected output: "k"

const strCopy = str.split()

console.log('strCopy = str.split()=', strCopy)

// expected output: Array ["The quick brown fox jumps over the lazy dog."]