Search completed in 1.08 seconds.
2130 results for "Array":
Your results are loading. Please wait...
VBArray.toArray - Archive of obsolete content
the vbarray.toarray method returns a standard javascript array converted from a vbarray.
... syntax safearray.toarray( ) remarks the required safearray reference is a vbarray object.
... the conversion translates the multidimensional vbarray into a single dimensional javascript array.
...And 7 more matches
Array.isArray() - JavaScript
the array.isarray() method determines whether the passed value is an array.
... array.isarray([1, 2, 3]); // true array.isarray({foo: 123}); // false array.isarray('foobar'); // false array.isarray(undefined); // false syntax array.isarray(value) parameters value the value to be checked.
... return value true if the value is an array; otherwise, false.
...And 6 more matches
TypedArray.prototype.subarray() - JavaScript
the subarray() method returns a new typedarray on the same arraybuffer store and with the same element types as for this typedarray object.
...typedarray is one of the typed array types.
... syntax typedarray.subarray([begin [,end]]) parameters begin optional element to begin at.
...And 6 more matches
ANGLE_instanced_arrays.drawArraysInstancedANGLE() - Web APIs
the angle_instanced_arrays.drawarraysinstancedangle() method of the webgl api renders primitives from array data like the gl.drawarrays() method.
... note: when using webgl2, this method is available as gl.drawarraysinstanced() by default.
... syntax void ext.drawarraysinstancedangle(mode, first, count, primcount); parameters mode a glenum specifying the type primitive to render.
...And 2 more matches
OES_vertex_array_object.createVertexArrayOES() - Web APIs
the oes_vertex_array_object.createvertexarrayoes() method of the webgl api creates and initializes a webglvertexarrayobject object that represents a vertex array object (vao) pointing to vertex array data and which provides names for different sets of vertex data.
... syntax webglvertexarrayobjectoes ext.createvertexarrayoes(); parameters none.
... return value a webglvertexarrayobject representing a vertex array object (vao) which points to vertex array data.
...And 2 more matches
OES_vertex_array_object.isVertexArrayOES() - Web APIs
the oes_vertex_array_object.isvertexarrayoes() method of the webgl api returns true if the passed object is a webglvertexarrayobject object.
... syntax glboolean ext.isvertexarrayoes(arrayobject); parameters arrayobject a webglvertexarrayobject (vao) object to test.
... return value a glboolean indicating whether the given object is a webglvertexarrayobject object (true) or not (false).
...And 2 more matches
OES_vertex_array_object.bindVertexArrayOES() - Web APIs
the oes_vertex_array_object.bindvertexarrayoes() method of the webgl api binds a passed webglvertexarrayobject object to the buffer.
... syntax void ext.bindvertexarrayoes(arrayobject); parameters arrayobject a webglvertexarrayobject (vao) object to bind.
... examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ...
... specifications specification status comment oes_vertex_array_objectthe definition of 'oes_vertex_array_object' in that specification.
OES_vertex_array_object.deleteVertexArrayOES() - Web APIs
the oes_vertex_array_object.deletevertexarrayoes() method of the webgl api deletes a given webglvertexarrayobject object.
... syntax void ext.deletevertexarrayoes(arrayobject); parameters arrayobject a webglvertexarrayobject (vao) object to delete.
... examples var ext = gl.getextension('oes_vertex_array_object'); var vao = ext.createvertexarrayoes(); ext.bindvertexarrayoes(vao); // ...
... ext.deletevertexarrayoes(vao); specifications specification status comment oes_vertex_array_objectthe definition of 'oes_vertex_array_object' in that specification.
XPCOM array guide
MozillaTechXPCOMGuideArrays
introduction array types mozilla has many array classes because each array is optimized for a particular usage pattern.
... this guide describes the available arrays as well as the enumerator classes that can be used to get to them.
... in this document the term array refers to a container for multiple objects with a numeric, zero-based index.
...And 108 more matches
TypedArray - JavaScript
a typedarray object describes an array-like view of an underlying binary data buffer.
... there is no global property named typedarray, nor is there a directly visible typedarray constructor.
... instead, there are a number of different global properties, whose values are typed array constructors for specific element types, listed below.
...And 90 more matches
BigUint64Array - JavaScript
the biguint64array typed array represents an array of 64-bit unsigned integers in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation).
... constructor biguint64array() creates a new biguint64array object.
...And 63 more matches
Uint8ClampedArray - JavaScript
the uint8clampedarray typed array represents an array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... constructor uint8clampedarray() creates a new uint8clampedarray object.
...And 63 more matches
BigInt64Array - JavaScript
the bigint64array typed array represents an array of 64-bit signed integers in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation).
... constructor bigint64array() creates a new bigint64array object.
...And 62 more matches
Float32Array - JavaScript
the float32array typed array represents an array of 32-bit floating point numbers (corresponding to the c float data type) in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... constructor float32array() creates a new float32array object.
...And 62 more matches
Float64Array - JavaScript
the float64array typed array represents an array of 64-bit floating point numbers (corresponding to the c double data type) in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... constructor float64array() creates a new float64array object.
...And 62 more matches
Int16Array - JavaScript
the int16array typed array represents an array of twos-complement 16-bit signed integers in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... constructor int16array() creates a new int16array object.
...And 62 more matches
Int32Array - JavaScript
the int32array typed array represents an array of twos-complement 32-bit signed integers in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... constructor int32array() creates a new int32array object.
...And 62 more matches
Int8Array - JavaScript
the int8array typed array represents an array of twos-complement 8-bit signed integers.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... constructor int8array() creates a new int8array object.
...And 62 more matches
Uint16Array - JavaScript
the uint16array typed array represents an array of 16-bit unsigned integers in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... constructor uint16array() creates a new uint16array object.
...And 62 more matches
Uint32Array - JavaScript
the uint32array typed array represents an array of 32-bit unsigned integers in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... constructor uint32array() creates a new uint32array object.
...And 62 more matches
Uint8Array - JavaScript
the uint8array typed array represents an array of 8-bit unsigned integers.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... constructor uint8array() creates a new uint8array object.
...And 62 more matches
Array - JavaScript
the javascript array class is a global object that is used in the construction of arrays; which are high-level, list-like objects.
... description arrays are list-like objects whose prototype has methods to perform traversal and mutation operations.
... neither the length of a javascript array nor the types of its elements are fixed.
...And 61 more matches
Arrays - Learn web development
previous overview: first steps next in the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name.
... here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
... objective: to understand what arrays are and how to manipulate them in javascript.
...And 50 more matches
Array.prototype.map() - JavaScript
the map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
... syntax let new_array = arr.map(function callback( currentvalue[, index[, array]]) { // return element for new_array }[, thisarg]) parameters callback function that is called for every element of arr.
... each time callback executes, the returned value is added to new_array.
...And 29 more matches
JavaScript typed arrays - JavaScript
javascript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers.
... as you may already know, array objects grow and shrink dynamically and can have any javascript value.
... javascript engines perform optimizations so that these arrays are fast.
...And 28 more matches
util/array - Archive of obsolete content
helper functions for working with arrays.
... globals functions has(array, element) returns true if the given array contains the element or false otherwise.
... a simplified version of array.indexof(element) >= 0.
...And 27 more matches
Array.prototype.reduce() - JavaScript
the reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
... the reducer function takes four arguments: accumulator (acc) current value (cur) current index (idx) source array (src) your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value.
... syntax arr.reduce(callback( accumulator, currentvalue, [, index[, array]] )[, initialvalue]) parameters callback a function to execute on each element in the array (except for the first, if no initialvalue is supplied).
...And 26 more matches
Array.prototype.forEach() - JavaScript
the foreach() method executes a provided function once for each array element.
... syntax arr.foreach(callback(currentvalue [, index [, array]])[, thisarg]) parameters callback function to execute on each element.
... it accepts between one and three arguments: currentvalue the current element being processed in the array.
...And 21 more matches
Array.prototype.filter() - JavaScript
the filter() method creates a new array with all elements that pass the test implemented by the provided function.
... syntax let newarray = arr.filter(callback(element[, index, [array]])[, thisarg]) parameters callback function is a predicate, to test each element of the array.
... it accepts three arguments: element the current element being processed in the array.
...And 20 more matches
Array.from() - JavaScript
the array.from() static method creates a new, shallow-copied array instance from an array-like or iterable object.
... syntax array.from(arraylike [, mapfn [, thisarg]]) parameters arraylike an array-like or iterable object to convert to an array.
... mapfn optional map function to call on every element of the array.
...And 20 more matches
ArrayType
arraytype represents c arrays syntax returns a new ctype representing an array data type.
... ctype arraytype() type[ length] ); parameters type: it represents the type of the elements or variable which is going to be present in an array length optional it denotes the number of entries present in an array or the number of elements that an array should contain.
... if you don't specify this parameter, the array's length is unspecified.
...And 17 more matches
Array.prototype.find() - JavaScript
the find() method returns the value of the first element in the provided array that satisfies the provided testing function.
... if you need the index of the found element in the array, use findindex().
... if you need to find the index of a value, use array.prototype.indexof().
...And 17 more matches
Array.prototype.slice() - JavaScript
the slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array.
... the original array will not be modified.
... if start is greater than the index range of the sequence, an empty array is returned.
...And 17 more matches
Array.prototype.reduceRight() - JavaScript
the reduceright() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.
... see also array.prototype.reduce() for left-to-right.
... syntax arr.reduceright(callback(accumulator, currentvalue[, index[, array]])[, initialvalue]) parameters callback function to execute on each value in the array, taking four arguments: accumulator the value previously returned in the last invocation of the callback, or initialvalue, if supplied.
...And 16 more matches
Array.prototype.every() - JavaScript
the every() method tests whether all elements in the array pass the test implemented by the provided function.
... syntax arr.every(callback(element[, index[, array]])[, thisarg]) parameters callback a function to test for each element, taking three arguments: element the current element being processed in the array.
... index optional the index of the current element being processed in the array.
...And 15 more matches
Array.prototype.concat() - JavaScript
the concat() method is used to merge two or more arrays.
... this method does not change the existing arrays, but instead returns a new array.
... syntax const new_array = old_array.concat([value1[, value2[, ...[, valuen]]]]) parameters valuen optional arrays and/or values to concatenate into a new array.
...And 14 more matches
Array.prototype.findIndex() - JavaScript
the findindex() method returns the index of the first element in the array that satisfies the provided testing function.
... see also the find() method, which returns the value of an array element, instead of its index.
... syntax arr.findindex(callback( element[, index[, array]] )[, thisarg]) parameters callback a function to execute on each value in the array until the function returns true, indicating that the satisfying element was found.
...And 14 more matches
Array.prototype.lastIndexOf() - JavaScript
the lastindexof() method returns the last index at which a given element can be found in the array, or -1 if it is not present.
... the array is searched backwards, starting at fromindex.
... syntax arr.lastindexof(searchelement[, fromindex]) parameters searchelement element to locate in the array.
...And 14 more matches
Array.prototype.some() - JavaScript
the some() method tests whether at least one element in the array passes the test implemented by the provided function.
... syntax arr.some(callback(element[, index[, array]])[, thisarg]) parameters callback a function to test for each element, taking three arguments: element the current element being processed in the array.
... indexoptional the index of the current element being processed in the array.
...And 14 more matches
Array.prototype.sort() - JavaScript
the sort() method sorts the elements of an array in place and returns the sorted array.
...if omitted, the array elements are converted to strings, then sorted according to each character's unicode code point value.
... return value the sorted array.
...And 14 more matches
SharedArrayBuffer - JavaScript
the sharedarraybuffer object is used to represent a generic, fixed-length raw binary data buffer, similar to the arraybuffer object, but in a way that they can be used to create views on shared memory.
... unlike an arraybuffer, a sharedarraybuffer cannot become detached.
... description allocating and sharing memory to share memory using sharedarraybuffer objects from one agent in the cluster to another (an agent is either the web page’s main program or one of its web workers), postmessage and structured cloning is used.
...And 14 more matches
TypedArray.from() - JavaScript
the typedarray.from() method creates a new typed array from an array-like or iterable object.
... this method is nearly the same as array.from().
... syntax typedarray.from(source[, mapfn[, thisarg]]) where typedarray is one of: int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array parameters source an array-like or iterable object to convert to a typed array.
...And 14 more matches
TypedArray.prototype.map() - JavaScript
the map() method creates a new typed array with the results of calling a provided function on every element in this typed array.
... this method has the same algorithm as array.prototype.map().
... typedarray is one of the typed array types here.
...And 14 more matches
VBArray - Archive of obsolete content
the vbarray object provides access to visual basic safe arrays.
... syntax varname = new vbarray(safearray) parameters varname the variable name to which the vbarray is assigned.
... safearray a vbarray value.
...And 13 more matches
JavaArray - Archive of obsolete content
summary core object a wrapped java array accessed from within javascript code is a member of the type javaarray.
... created by any java method which returns an array.
... in addition, you can create a javaarray with an arbitrary data type using the newinstance method of the array class: public static object newinstance(class componenttype, int length) throws negativearraysizeexception description the javaarray object is an instance of a java array that is created in or passed to javascript.
...And 13 more matches
Test your skills: Arrays - Learn web development
this aim of this skill test is to assess whether you've understood our arrays article.
... arrays 1 let's start off with some basic array practice.
... in this task we'd like you to create an array of three items, stored inside a variable called myarray.
...And 13 more matches
nsIArray
xpcom/ds/nsiarray.idlscriptable this interface implements an array object.
...indexes are zero-based, such that the last element in the array is stored at the index length-1.
... for an array which can be modified, see nsimutablearray.
...And 13 more matches
nsIMutableArray
xpcom/ds/nsimutablearray.idlscriptable this interface is a subclass of nsiarray that provides arrays that are mutable; that is, they can be altered programmatically.
... inherits from: nsiarray last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) consumers of nsiarray should not queryinterface to nsimutablearray unless they own the array.
... as above, it is legal to add null elements to the array.
...And 13 more matches
Working with ArrayBuffers
an arraybuffer is a simply byte array.
... the js-ctypes equivalent is a ctypes.uint8_t.array(###) (ctypes.unsigned_char are also ctypes.uint8_t).
... bug 732936 includes a discussion of working with an arraybuffer.
...And 13 more matches
Array.prototype.push() - JavaScript
the push() method adds one or more elements to the end of an array and returns the new length of the array.
... syntax arr.push([element1[, ...[, elementn]]]) parameters elementn the element(s) to add to the end of the array.
... description the push method appends values to an array.
...And 13 more matches
TypedArray.prototype.filter() - JavaScript
the filter() method creates a new typed array with all elements that pass the test implemented by the provided function.
... this method has the same algorithm as array.prototype.filter().
... typedarray is one of the typed array types here.
...And 13 more matches
JS_NewArrayObject
create a new array object.
... syntax jsobject * js_newarrayobject(jscontext *cx, const js::handlevaluearray& contents); // added in spidermonkey 31 jsobject * js_newarrayobject(jscontext *cx, size_t length); // added in spidermonkey 31 jsobject * js_newarrayobject(jscontext *cx, int length, jsval *vector); // obsolete since jsapi 30 name type description cx jscontext * the context in which to create the new array.
... contents js::handlevaluearray& reference to the initial values for the array's elements.
...And 12 more matches
TypedArray.prototype.find() - JavaScript
the find() method returns a value in the typed array, if an element satisfies the provided testing function.
...typedarray is one of the typed array types here.
... see also the findindex() method, which returns the index of a found element in the typed array instead of its value.
...And 12 more matches
TypedArray.prototype.findIndex() - JavaScript
the findindex() method returns an index in the typed array, if an element in the typed array satisfies the provided testing function.
... see also the find() method, which returns the value of a found element in the typed array instead of its index.
... syntax typedarray.findindex(callback[, thisarg]) parameters callback function to execute on each value in the typed array, taking three arguments: element the current element being processed in the typed array.
...And 12 more matches
TypedArray.prototype.some() - JavaScript
the some() method tests whether some element in the typed array passes the test implemented by the provided function.
... this method has the same algorithm as array.prototype.some().
... typedarray is one of the typed array types here.
...And 12 more matches
JS::HandleValueArray
this article covers features introduced in spidermonkey 31 a handle to an array of rooted values.
... syntax js::handlevaluearray(const js::rootedvalue& value); js::handlevaluearray(const js::autovaluevector& values); js::handlevaluearray(const js::autovaluearray<n>& values); js::handlevaluearray(const js::callargs& args); js::handlevaluearray::frommarkedlocation(size_t len, const js::value *elements); js::handlevaluearray::subarray(const js::handlevaluearray& values, size_t startindex, size_t len); js::handlevaluearray::empty(); name type description value js::rootedvalue &amp; an element of newly created 1-length array.
... values js::autovaluevector &amp; elements of newly created array.
...And 11 more matches
Array.prototype.indexOf() - JavaScript
the indexof() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
... syntax arr.indexof(searchelement[, fromindex]) parameters searchelement element to locate in the array.
...if the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched.
...And 11 more matches
Array.prototype.splice() - JavaScript
the splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
... syntax let arrdeleteditems = array.splice(start[, deletecount[, item1[, item2[, ...]]]]) parameters start the index at which to start changing the array.
... if greater than the length of the array, start will be set to the length of the array.
...And 11 more matches
TypedArray.prototype.lastIndexOf() - JavaScript
the lastindexof() method returns the last index at which a given element can be found in the typed array, or -1 if it is not present.
... the typed array is searched backwards, starting at fromindex.
... this method has the same algorithm as array.prototype.lastindexof().
...And 11 more matches
TypedArray.prototype.reduce() - JavaScript
the reduce() method applies a function against an accumulator and each value of the typed array (from left-to-right) has to reduce it to a single value.
... this method has the same algorithm as array.prototype.reduce().
... typedarray is one of the typed array types here.
...And 11 more matches
TypedArray.prototype.reduceRight() - JavaScript
the reduceright() method applies a function against an accumulator and each value of the typed array (from right-to-left) has to reduce it to a single value.
... this method has the same algorithm as array.prototype.reduceright().
... typedarray is one of the typed array types here.
...And 11 more matches
Uint16Array() constructor - JavaScript
the uint16array() typed array constructor creates an array of 16-bit unsigned integers in the platform byte order.
... syntax new uint16array(); // new in es2017 new uint16array(length); new uint16array(typedarray); new uint16array(object); new uint16array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
...And 11 more matches
Array.prototype.fill() - JavaScript
the fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length).
... it returns the modified array.
... syntax arr.fill(value[, start[, end]]) parameters value value to fill the array with.
...And 10 more matches
Array.prototype.includes() - JavaScript
the includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
... fromindex optional the position in this array at which to begin searching for valuetofind.
... 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).
...And 10 more matches
TypedArray.prototype.every() - JavaScript
the every() method tests whether all elements in the typed array pass the test implemented by the provided function.
... this method has the same algorithm as array.prototype.every().
... typedarray is one of the typed array types here.
...And 10 more matches
Array comprehensions - Archive of obsolete content
the array comprehensions syntax is non-standard and removed starting with firefox 58.
... for future-facing usages, consider using array.prototype.map, array.prototype.filter, arrow functions, and spread syntax.
... the array comprehension syntax was a javascript expression which allowed you to quickly assemble a new array based on an existing one.
...And 9 more matches
JS_SetArrayLength
syntax bool js_setarraylength(jscontext *cx, js::handle<jsobject*> obj, uint32_t length); name type description cx jscontext * the context in which to change the length of the array.
... obj js::handle&lt;jsobject*&gt; the array to modify.
... length uint32_t number of array elements to set.
...And 9 more matches
ArrayBuffer - JavaScript
the arraybuffer object is used to represent a generic, fixed-length raw binary data buffer.
... it is an array of bytes, often referred to in other languages as a "byte array".you cannot directly manipulate the contents of an arraybuffer; instead, you create one of the typed array objects or a dataview object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.
... the arraybuffer() constructor creates a new arraybuffer of the given length in bytes.
...And 9 more matches
TypedArray.prototype.forEach() - JavaScript
the foreach() method executes a provided function once per array element.
... this method has the same algorithm as array.prototype.foreach().
... typedarray is one of the typed array types here.
...And 9 more matches
TypedArray.prototype.indexOf() - JavaScript
the indexof() method returns the first index at which a given element can be found in the typed array, or -1 if it is not present.
... this method has the same algorithm as array.prototype.indexof().
... typedarray is one of the typed array types here.
...And 9 more matches
VBArray.lbound - Archive of obsolete content
the vbarray.lbound method returns the lowest index value used in the specified dimension of a vbarray.
... syntax safearray.lbound(dimension) remarks if the vbarray is empty, the lbound method returns undefined.
... if dimension is greater than the number of dimensions in the vbarray, or is negative, the method generates a "subscript out of range" error.
...And 8 more matches
WebGLRenderingContext.enableVertexAttribArray() - Web APIs
the webglrenderingcontext method enablevertexattribarray(), part of the webgl api, turns on the generic vertex attribute array at the specified index into the list of attribute arrays.
... you can disable the attribute array by calling disablevertexattribarray().
... either way, since attributes cannot be used unless enabled, and are disabled by default, you need to call enablevertexattribarray() to enable individual attributes so that they can be used.
...And 8 more matches
Array.prototype.length - JavaScript
the length property of an object which is an instance of type array sets or returns the number of elements in that array.
... the value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
... var namelista = new array(4294967296); //2 to the 32nd power = 4294967296 var namelistc = new array(-100) //negative sign console.log(namelista.length); //rangeerror: invalid array length console.log(namelistc.length); //rangeerror: invalid array length var namelistb = []; namelistb.length = math.pow(2,32)-1; //set array length less than 2 to the 32nd power console.log(namelistb.length); //4294967295 you can set the length property to...
...And 8 more matches
BigInt64Array() constructor - JavaScript
the bigint64array() typed array constructor creates a new bigint64array object, which is, an array of 64-bit signed integers in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation).
... syntax new bigint64array(); new bigint64array(length); new bigint64array(typedarray); new bigint64array(object); new bigint64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
...And 8 more matches
BigUint64Array() constructor - JavaScript
the biguint64array() typed array constructor creates a new biguint64array object, which is, an array of 64-bit unsigned integers in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or by using standard array index syntax (that is, using bracket notation).
... syntax new biguint64array(); new biguint64array(length); new biguint64array(typedarray); new biguint64array(object); new biguint64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
...And 8 more matches
Float32Array() constructor - JavaScript
the float32array() typed array constructor creates a new float32array object, which is, an array of 32-bit floating point numbers (corresponding to the c float data type) in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... syntax new float32array(); // new in es2017 new float32array(length); new float32array(typedarray); new float32array(object); new float32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
...And 8 more matches
Float64Array() constructor - JavaScript
the float64array() typed array constructor creates a new float64array object, which is, an array of 64-bit floating point numbers (corresponding to the c double data type) in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... syntax new float64array(); // new in es2017 new float64array(length); new float64array(typedarray); new float64array(object); new float64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
...And 8 more matches
Int16Array() constructor - JavaScript
the int16array() typed array constructor creates an array of twos-complement 16-bit signed integers in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... syntax new int16array(); // new in es2017 new int16array(length); new int16array(typedarray); new int16array(object); new int16array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
...And 8 more matches
Int32Array() constructor - JavaScript
the int32array() typed array constructor creates an array of twos-complement 32-bit signed integers in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... syntax new int32array(); // new in es2017 new int32array(length); new int32array(typedarray); new int32array(object); new int32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
...And 8 more matches
Int8Array() constructor - JavaScript
the int8array() constructor creates a typed array of twos-complement 8-bit signed integers.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... syntax new int8array(); // new in es2017 new int8array(length); new int8array(typedarray); new int8array(object); new int8array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
...And 8 more matches
TypedArray.prototype.slice() - JavaScript
the slice() method returns a shallow copy of a portion of a typed array into a new typed array object.
... this method has the same algorithm as array.prototype.slice().
... typedarray is one of the typed array types here.
...And 8 more matches
Uint32Array() constructor - JavaScript
the uint32array() typed array constructor creates an array of 32-bit unsigned integers in the platform byte order.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... syntax new uint32array(); // new in es2017 new uint32array(length); new uint32array(typedarray); new uint32array(object); new uint32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
...And 8 more matches
Uint8Array() constructor - JavaScript
the uint8array() constructor creates a typed array of 8-bit unsigned integers.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... syntax new uint8array(); // new in es2017 new uint8array(length); new uint8array(typedarray); new uint8array(object); new uint8array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
...And 8 more matches
Uint8ClampedArray() constructor - JavaScript
the uint8clampedarray() constructor creates a typed array of 8-bit unsigned integers clamped to 0-255; if you specified a value that is out of the range of [0,255], 0 or 255 will be set instead; if you specify a non-integer, the nearest integer will be set.
...once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
... syntax new uint8clampedarray(); // new in es2017 new uint8clampedarray(length); new uint8clampedarray(typedarray); new uint8clampedarray(object); new uint8clampedarray(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
...And 8 more matches
ArrayBuffer.transfer() - Archive of obsolete content
the static arraybuffer.transfer() method returns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength.
... syntax arraybuffer.transfer(oldbuffer [, newbytelength]); parameters oldbuffer an arraybuffer object from which to transfer.
... newbytelength the byte length of the new arraybuffer object.
...And 7 more matches
VBArray.ubound - Archive of obsolete content
the vbarray.ubound method returns the highest index value used in the specified dimension of the vbarray.
... syntax safearray.ubound(dimension) parameters safearray a vbarray object.
... dimension optional the dimension of the vbarray for which the higher bound index is wanted.
...And 7 more matches
JS::AutoIdArray
this article covers features introduced in spidermonkey 17 take ownership of a jsidarray and free it later.
... syntax autoidarray(jscontext *cx, jsidarray *ida); name type description cx jscontext * the context in which to add the root.
... ida jsidarray * a pointer to jsidarray to take the ownership.
...And 7 more matches
JS::AutoValueArray
this article covers features introduced in spidermonkey 31 root an internal fixed-size array of js::values.
... syntax js::autovaluearray<n> vp(cx); name type description cx jscontext * the context in which to add the root.
... n size_t size of a js::value array.
...And 7 more matches
JS_HasArrayLength
determines if an object has an array length property.
... syntax jsbool js_hasarraylength(jscontext *cx, jsobject *obj, jsuint *lengthp); name type description cx jscontext * pointer to a js context from which to derive runtime information.
... obj jsobject * array object to get the length of.
...And 7 more matches
TypeError: can't delete non-configurable array element - JavaScript
the javascript exception "can't delete non-configurable array element" occurs when it was attempted to shorten the length of an array, but one of the array's elements is non-configurable.
... message typeerror: can't delete non-configurable array element (firefox) typeerror: cannot delete property '2' of [object array] (chrome) error type typeerror what went wrong?
... it was attempted to shorten the length of an array, but one of the array's elements is non-configurable.
...And 7 more matches
Array.prototype.join() - JavaScript
the join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.
... if the array has only one item, then that item will be returned without using the separator.
... syntax arr.join([separator]) parameters separator optional specifies a string to separate each pair of adjacent elements of the array.
...And 7 more matches
Array.prototype.pop() - JavaScript
the pop() method removes the last element from an array and returns that element.
... this method changes the length of the array.
... syntax arrname.pop() return value the removed element from the array; undefined if the array is empty.
...And 7 more matches
Array.prototype.reverse() - JavaScript
the reverse() method reverses an array in place.
... the first array element becomes the last, and the last array element becomes the first.
... syntax a.reverse() return value the reversed array.
...And 7 more matches
Array.observe() - Archive of obsolete content
the array.observe() method was used for asynchronously observing changes to arrays, similar to object.observe() for objects.
... syntax array.observe(arr, callback) parameters arr the array to be observed.
... callback the function called each time changes are made, with the following argument: changes an array of objects each representing a change.
...And 6 more matches
VBArray.getItem - Archive of obsolete content
the vbarray.getitem method returns the item at the specified location.
... syntax safearray.getitem(dimension1[, dimension2, ...], dimensionn) parameters safearray a vbarray object.
... dimension1, ..., dimensionn specifies the exact location of the desired element of the vbarray.
...And 6 more matches
TypeError: Reduce of empty array with no initial value - JavaScript
the javascript exception "reduce of empty array with no initial value" occurs when a reduce function is used.
... message typeerror: reduce of empty array with no initial value error type typeerror what went wrong?
... in javascript, there are several reduce functions: array.prototype.reduce(), array.prototype.reduceright() and typedarray.prototype.reduce(), typedarray.prototype.reduceright()).
...And 6 more matches
Array.prototype.flatMap() - JavaScript
the flatmap() method first maps each element using a mapping function, then flattens the result into a new array.
... syntax var new_array = arr.flatmap(function callback(currentvalue[, index[, array]]) { // return element for new_array }[, thisarg]) parameters callback function that produces an element of the new array, taking three arguments: currentvalue the current element being processed in the array.
... indexoptional the index of the current element being processed in the array.
...And 6 more matches
Array.prototype.toLocaleString() - JavaScript
the tolocalestring() method returns a string representing the elements of the array.
... syntax arr.tolocalestring([locales[, options]]); parameters locales optional a string with a bcp 47 language tag, or an array of such strings.
... return value a string representing the elements of the array.
...And 6 more matches
TypedArray.prototype.fill() - JavaScript
the fill() method fills all the elements of a typed array from a start index to an end index with a static value.
... this method has the same algorithm as array.prototype.fill().
... typedarray is one of the typed array types here.
...And 6 more matches
TypedArray.prototype.join() - JavaScript
the join() method joins all elements of an array into a string.
... this method has the same algorithm as array.prototype.join().
... typedarray is one of the typed array types here.
...And 6 more matches
TypedArray.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified array and its elements.
... this method has the same algorithm as array.prototype.tostring().
... typedarray is one of the typed array types here.
...And 6 more matches
VBArray.dimensions - Archive of obsolete content
the vbarray.dimensions method returns the number of dimensions in a vbarray.
... syntax array.dimensions( ) remarks the required array is a vbarray object.
... example the dimensions method provides a way to retrieve the number of dimensions in a specified vbarray.
...And 5 more matches
Body.arrayBuffer() - Web APIs
WebAPIBodyarrayBuffer
the arraybuffer() method of the body mixin takes a response stream and reads it to completion.
... it returns a promise that resolves with an arraybuffer.
... syntax response.arraybuffer().then(function(buffer) { // do something with buffer }); parameters none.
...And 5 more matches
OES_vertex_array_object - Web APIs
the oes_vertex_array_object extension is part of the webgl api and provides vertex array objects (vaos) which encapsulate vertex array states.
... constants this extension exposes one new constant, which can be used in the gl.getparameter() method: ext.vertex_array_binding_oes returns a webglvertexarrayobject object when used in the gl.getparameter() method as the pname parameter.
... ext.createvertexarrayoes() creates a new webglvertexarrayobject.
...And 5 more matches
PluginArray - Web APIs
the pluginarray interface is used to store a list of plugin objects describing the available plugins; it's returned by the window.navigator.plugins property.
... the pluginarray is not a javascript array, but has the length property and supports accessing individual items using bracket notation (plugins[2]), as well as via item(index) and nameditem("name") methods.
... note: own properties of pluginarray objects are no longer enumerable in the latest browser versions.
...And 5 more matches
Array() constructor - JavaScript
the array() constructor is used to create array objects.
... syntax [element0, element1, ..., elementn] new array(element0, element1[, ...[, elementn]]) new array(arraylength) parameters elementn a javascript array is initialized with the given elements, except in the case where a single argument is passed to the array constructor and that argument is a number (see the arraylength parameter below).
... note that this special case only applies to javascript arrays created with the array constructor, not array literals created with the bracket syntax.
...And 5 more matches
Array.prototype.flat() - JavaScript
the flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
... syntax var newarray = arr.flat([depth]); parameters depth optional the depth level specifying how deep a nested array structure should be flattened.
... return value a new array with the sub-array elements concatenated into it.
...And 5 more matches
ArrayBuffer.prototype.slice() - JavaScript
the slice() method returns a new arraybuffer whose contents are a copy of this arraybuffer's bytes from begin, inclusive, up to end, exclusive.
... syntax arraybuffer.slice(begin[, end]) parameters begin zero-based byte index at which to begin slicing.
...if end is unspecified, the new arraybuffer contains all bytes from begin to the end of this arraybuffer.
...And 5 more matches
TypedArray.prototype.copyWithin() - JavaScript
the copywithin() method copies the sequence of array elements within the array to the position starting at target.
...the end argument is optional and defaults to the length of the array.
... this method has the same algorithm as array.prototype.copywithin.
...And 5 more matches
TypedArray.prototype.set() - JavaScript
the set() method stores multiple values in the typed array, reading input values from a specified array.
... syntax typedarray.set(array[, offset]) typedarray.set(typedarray[, offset]) parameters array the array from which to copy values.
... all values from the source array are copied into the target array, unless the length of the source array plus the offset exceeds the length of the target array, in which case an exception is thrown.
...And 5 more matches
TypedArray.prototype.sort() - JavaScript
the sort() method sorts the elements of a typed array numerically in place and returns the typed array.
... this method has the same algorithm as array.prototype.sort(), except that sorts the values numerically instead of as strings.
... typedarray is one of the typed array types here.
...And 5 more matches
JS_GetArrayLength
retrieve the number of elements in an array object.
... syntax bool js_getarraylength(jscontext *cx, js::handle<jsobject*> obj, uint32_t *lengthp); name type description cx jscontext * the context in which to look up the array's length.
...on success, *lengthp receives the length of the array.
...And 4 more matches
XRInputSourceArray - Web APIs
the interface xrinputsourcearray represents a live list of webxr input sources, and is used as the return value of the xrsession property inputsources.
... in addition to being able to access the input sources in the list using standard array notation (that is, with index numbers insize square brackets), methods are available to allow the use of iterators and the foreach() method is also available.
... properties the following properties are available on xrinputsourcearray objects.
...And 4 more matches
RangeError: invalid array length - JavaScript
the javascript exception "invalid array length" occurs when creating an array or an arraybuffer which has a length which is either negative or larger or equal to 232, or when setting the array.length property to a value which is either negative or larger or equal to 232.
... message rangeerror: array length must be a finite positive integer (edge) rangeerror: invalid array length (firefox) rangeerror: invalid array length (chrome) rangeerror: invalid array buffer length (chrome) error type rangeerror what went wrong?
... an invalid array length might appear in these situations: when creating an array or an arraybuffer which has a length which is either negative or larger or equal to 232, or when setting the array.length property to a value which is either negative or larger or equal to 232.
...And 4 more matches
Array.prototype.copyWithin() - JavaScript
the copywithin() method shallow copies part of an array to another location in the same array and returns it without modifying its length.
... return value the modified array.
... description the copywithin works like c and c++'s memmove, and is a high-performance method to shift the data of an array.
...And 4 more matches
Array.prototype.shift() - JavaScript
the shift() method removes the first element from an array and returns that removed element.
... this method changes the length of the array.
... syntax arr.shift() return value the removed element from the array; undefined if the array is empty.
...And 4 more matches
Array.prototype.values() - JavaScript
the values() method returns a new array iterator object that contains the values for each index in the array.
... syntax arr.values() return value a new array iterator object.
... examples iteration using for...of loop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" array.prototype.values is default implementation of array.prototype[symbol.iterator].
...And 4 more matches
SharedArrayBuffer() constructor - JavaScript
note that sharedarraybuffer was disabled by default in all major browsers on 5 january, 2018 in response to spectre.
... the sharedarraybuffer() constructor is used to create a sharedarraybuffer object representing a generic, fixed-length raw binary data buffer, similar to the arraybuffer object.
... syntax new sharedarraybuffer([length]) parameters length the size, in bytes, of the array buffer to create.
...And 4 more matches
TypedArray.name - JavaScript
the typedarray.name property represents a string value of the typed array constructor name.
... property attributes of typedarray.name writable no enumerable no configurable no description typedarray objects differ from each other in the number of bytes per element and in the way the bytes are interpreted.
... the name property describes of what data type the array consists.
...And 4 more matches
TypedArray.of() - JavaScript
the typedarray.of() method creates a new typed array from a variable number of arguments.
... this method is nearly the same as array.of().
... syntax typedarray.of(element0[, element1[, ...[, elementn]]]) where typedarray is one of: int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array parameters elementn elements of which to create the typed array.
...And 4 more matches
Array.unobserve() - Archive of obsolete content
the array.unobserve() method was used to remove observers set by array.observe(), but has been deprecated and removed from browsers.
... syntax array.unobserve(arr, callback) parameters arr the array to stop observing.
... callback the reference to the observer to stop calling each time changes are made on the array arr.
...And 3 more matches
Array - MDN Web Docs Glossary: Definitions of Web-related terms
an array is an ordered collection of data (either primitive or object depending upon the language).
... arrays are used to store multiple values in a single variable.
... each item in an array has a number attached to it, called a numeric index, that allows you to access it.
...And 3 more matches
JS_DestroyIdArray
free a jsidarray.
... syntax void js_destroyidarray(jscontext *cx, jsidarray *ida); name type description cx jscontext * a context.
... ida jsidarray * the jsidarray to free.
...And 3 more matches
JS_GetArrayPrototype
this article covers features introduced in spidermonkey 24 retrieves the original, canonical array.prototype for an object's global object.
... syntax jsobject * js_getarrayprototype(jscontext *cx, js::handleobject forobj); name type description cx jscontext * pointer to a javascript context from which to derive runtime information.
... forobj js::handleobject an object from the global whose array.prototype is being retrieved.
...And 3 more matches
JS_IdArrayGet
this article covers features introduced in spidermonkey 17 get the item of a jsidarray.
... syntax jsid js_idarrayget(jscontext *cx, jsidarray *ida, unsigned index) name type description cx jscontext * a context.
... ida jsidarray * the jsidarray to get the length.
...And 3 more matches
JS_IsArrayObject
determine if a specified object is an array.
... syntax bool js_isarrayobject(jscontext *cx, js::handlevalue value, bool *isarray); bool js_isarrayobject(jscontext *cx, js::handleobject obj, bool *isarray); // obsolete since jsapi 44 bool js_isarrayobject(jscontext *cx, js::handlevalue value); bool js_isarrayobject(jscontext *cx, js::handleobject obj); name type description cx jscontext * a context.
... isarray bool whether the value/object is an array.
...And 3 more matches
mozIStorageBindingParamsArray
the mozistoragebindingparamsarray interface is a container for mozistoragebindingparams objects, and is used to store sets of bound parameters that will be used by the mozistoragestatement.executeasync().
... storage/public/mozistoragebindingparamsarray.idlscriptable please add a summary to this article.
... last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports you can only create these objects by calling the mozistoragestatement.newbindingparamsarray().
...And 3 more matches
mozIStorageValueArray
the mozistoragevaluearray interface obtains provides methods to obtain data from a given result.
... storage/public/mozistoragevaluearray.idlscriptable please add a summary to this article.
... long gettypeofindex(in unsigned long aindex); long getint32(in unsigned long aindex); long long getint64(in unsigned long aindex); double getdouble(in unsigned long aindex); autf8string getutf8string(in unsigned long aindex); astring getstring(in unsigned long aindex); void getblob(in unsigned long aindex, out unsigned long adatasize, [array,size_is(adatasize)] out octet adata); boolean getisnull(in unsigned long aindex); attributes attribute type description numentries unsigned long the number of entries in the array.
...And 3 more matches
nsISupportsArray
xpcom/ds/nsisupportsarray.idlscriptable please add a summary to this article.
... inherits from: nsicollection last changed in gecko 1.7 method overview boolean appendelements(in nsisupportsarray aelements); violates the xpcom interface guidelines nsisupportsarray clone(); void compact(); void deleteelementat(in unsigned long aindex); void deletelastelement(in nsisupports aelement); nsisupports elementat(in unsigned long aindex); violates the xpcom interface guidelines boolean enumeratebackwards(in nsisupportsarrayenumfunc afunc, in voidptr adata); violates the xpcom interface guidelines boolean enumerateforwards(in nsisupportsarrayenumfunc afunc, in voidptr adata); violates the xpcom interface guidelines boolean equals([const] in nsisupportsarray other); violates the xpcom interface guidelines long getindexof(in nsisupports apossibleelement); lo...
...ement); long indexof([const] in nsisupports apossibleelement); violates the xpcom interface guidelines long indexofstartingat([const] in nsisupports apossibleelement, in unsigned long astartindex); violates the xpcom interface guidelines boolean insertelementat(in nsisupports aelement, in unsigned long aindex); violates the xpcom interface guidelines boolean insertelementsat(in nsisupportsarray aother, in unsigned long aindex); violates the xpcom interface guidelines long lastindexof([const] in nsisupports apossibleelement); violates the xpcom interface guidelines boolean moveelement(in long afrom, in long ato); violates the xpcom interface guidelines boolean removeelementat(in unsigned long aindex); violates the xpcom interface guidelines boolean removeelementsat(in unsigned lo...
...And 3 more matches
WebGL2RenderingContext.createVertexArray() - Web APIs
the webgl2renderingcontext.createvertexarray() method of the webgl 2 api creates and initializes a webglvertexarrayobject object that represents a vertex array object (vao) pointing to vertex array data and which provides names for different sets of vertex data.
... syntax webglvertexarrayobject gl.createvertexarray(); parameters none.
... return value a webglvertexarrayobject representing a vertex array object (vao) which points to vertex array data.
...And 3 more matches
WebGL2RenderingContext.drawArraysInstanced() - Web APIs
the webgl2renderingcontext.drawarraysinstanced() method of the webgl 2 api renders primitives from array data like the gl.drawarrays() method.
... note: when using webgl 1, the angle_instanced_arrays extension can provide this method, too.
... syntax void gl.drawarraysinstanced(mode, first, count, instancecount); parameters mode a glenum specifying the type primitive to render.
...And 3 more matches
WebGL2RenderingContext.isVertexArray() - Web APIs
the webgl2renderingcontext.isvertexarray() method of the webgl api returns true if the passed object is a valid webglvertexarrayobject object.
... syntax glboolean gl.isvertexarray(vertexarray); parameters vertexarray a webglvertexarrayobject (vao) object to test.
... return value a glboolean indicating whether the given object is a valid webglvertexarrayobject object (true) or not (false).
...And 3 more matches
XRInputSourceArray.forEach() - Web APIs
the xrinputsourcearray method foreach() executes the specified callback once for each input source in the array, starting at index 0 and progressing until the end of the list.
... syntax xrinputsourcearray.foreach(callback, thisarg); parameters callback a function to execute once for each entry in the array xrinputsourcearray.
... the callback accepts up to three parameters: currentvalue a xrinputsource object which is the value of the item from within the xrinputsourcearray which is currently being processed.
...And 3 more matches
get Array[@@species] - JavaScript
the array[@@species] accessor property returns the array constructor.
... syntax array[symbol.species] return value the array constructor.
... description the species accessor property returns the default constructor for array objects.
...And 3 more matches
Array.of() - JavaScript
the array.of() method creates a new array instance from a variable number of arguments, regardless of number or type of the arguments.
... the difference between array.of() and the array constructor is in the handling of integer arguments: array.of(7) creates an array with a single element, 7, whereas array(7) creates an empty array with a length property of 7 (note: this implies an array of 7 empty slots, not slots with actual undefined values).
... array.of(7); // [7] array.of(1, 2, 3); // [1, 2, 3] array(7); // array of 7 empty slots array(1, 2, 3); // [1, 2, 3] syntax array.of(element0[, element1[, ...[, elementn]]]) parameters elementn elements used to create the array.
...And 3 more matches
Array.prototype.toString() - JavaScript
the tostring() method returns a string representing the specified array and its elements.
... syntax arr.tostring() return value a string representing the elements of the array.
... description the array object overrides the tostring method of object.
...And 3 more matches
ArrayBuffer() constructor - JavaScript
the arraybuffer() constructor is used to create arraybuffer objects.
... syntax new arraybuffer(length) parameters length the size, in bytes, of the array buffer to create.
... return value a new arraybuffer object of the specified size.
...And 3 more matches
TypedArray.prototype.includes() - JavaScript
the includes() method determines whether a typed array includes a certain element, returning true or false as appropriate.
... this method has the same algorithm as array.prototype.includes().
... typedarray is one of the typed array types here.
...And 3 more matches
TypedArray.prototype.reverse() - JavaScript
the reverse() method reverses a typed array in place.
... the first typed array element becomes the last and the last becomes the first.
... this method has the same algorithm as array.prototype.reverse().
...And 3 more matches
TypedArray.prototype.toLocaleString() - JavaScript
the tolocalestring() method returns a string representing the elements of the typed array.
...this method has the same algorithm as array.prototype.tolocalestring() and, as the typed array elements are numbers, the same algorithm as number.prototype.tolocalestring() applies for each element.
... typedarray is one of the typed array types here.
...And 3 more matches
stroke-dasharray - SVG: Scalable Vector Graphics
the stroke-dasharray attribute is a presentation attribute defining the pattern of dashes and gaps used to paint the outline of the shape; note: as a presentation attribute, stroke-dasharray can be used as a css property.
...e> <ellipse> <path> <line> <polygon> <polyline> <rect> <text> <textpath> <tref> <tspan> html,body,svg { height:100% } <svg viewbox="0 0 30 10" xmlns="http://www.w3.org/2000/svg"> <!-- no dashes nor gaps --> <line x1="0" y1="1" x2="30" y2="1" stroke="black" /> <!-- dashes and gaps of the same size --> <line x1="0" y1="3" x2="30" y2="3" stroke="black" stroke-dasharray="4" /> <!-- dashes and gaps of different sizes --> <line x1="0" y1="5" x2="30" y2="5" stroke="black" stroke-dasharray="4 1" /> <!-- dashes and gaps of various sizes with an odd number of values --> <line x1="0" y1="7" x2="30" y2="7" stroke="black" stroke-dasharray="4 1 2" /> <!-- dashes and gaps of various sizes with an even number of values --> <line x1="...
...0" y1="9" x2="30" y2="9" stroke="black" stroke-dasharray="4 1 2 3" /> </svg> usage notes value none | <dasharray> default value none animatable yes <dasharray> a list of comma and/or white space separated <length>s and <percentage>s that specify the lengths of alternating dashes and gaps.
...And 3 more matches
JS_IdArrayLength
this article covers features introduced in spidermonkey 17 get the length of a jsidarray.
... syntax int js_idarraylength(jscontext *cx, jsidarray *ida); name type description cx jscontext * a context.
... ida jsidarray * the jsidarray to get the length of.
...And 2 more matches
ANGLE_instanced_arrays - Web APIs
the angle_instanced_arrays extension is part of the webgl api and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type.
... constants this extension exposes one new constant, which can be used in the gl.getvertexattrib() method: ext.vertex_attrib_array_divisor_angle returns a glint describing the frequency divisor used for instanced rendering when used in the gl.getvertexattrib() as the pname parameter.
... ext.drawarraysinstancedangle() behaves identically to gl.drawarrays() except that multiple instances of the range of elements are executed, and the instance advances for each iteration.
...And 2 more matches
Blob.arrayBuffer() - Web APIs
WebAPIBlobarrayBuffer
the arraybuffer() method in the blob interface returns a promise that resolves with the contents of the blob as binary data contained in an arraybuffer.
... syntax var bufferpromise = blob.arraybuffer(); blob.arraybuffer().then(buffer => /* process the arraybuffer */); var buffer = await blob.arraybuffer(); parameters none.
... returns a promise that resolves with an arraybuffer that contains the blob's data in binary form.
...And 2 more matches
FileReader.readAsArrayBuffer() - Web APIs
the filereader interface's readasarraybuffer() method is used to start reading the contents of a specified blob or file.
...at that time, the result attribute contains an arraybuffer representing the file's data.
... newer api available the blob.arraybuffer() method is a newer promise-based api to read a file as an array buffer.
...And 2 more matches
FileReaderSync.readAsArrayBuffer() - Web APIs
the readasarraybuffer() method of the filereadersync interface allows to read file or blob objects in a synchronous way into an arraybuffer.
... syntax arraybuffer readasarraybuffer( in blob blob ); parameters blob the dom file or blob to read into the file or arraybuffer.
... return value an arraybuffer representing the file's data.
...And 2 more matches
MimeTypeArray - Web APIs
the mimetypearray interface returns an array of mimetype instances, each of which contains information about a supported browser plugins.
... properties mimetypearray.length the number of items in the array.
... methods mimetypearray.item() returns the mimetype object with the specified index.
...And 2 more matches
PushMessageData.arrayBuffer() - Web APIs
the arraybuffer()method of the pushmessagedata interface extracts push message data as an arraybuffer object.
... syntax var myarraybuffer = pushevent.data.arraybuffer(); parameters none.
... returns an arraybuffer.
...And 2 more matches
WebGL2RenderingContext.bindVertexArray() - Web APIs
the webgl2renderingcontext.bindvertexarray() method of the webgl 2 api binds a passed webglvertexarrayobject object to the buffer.
... syntax void gl.bindvertexarray(vertexarray); parameters vertexarray a webglvertexarrayobject (vao) object to bind.
... examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
...And 2 more matches
WebGL2RenderingContext.deleteVertexArray() - Web APIs
the webgl2renderingcontext.deletevertexarray() method of the webgl 2 api deletes a given webglvertexarrayobject object.
... syntax void gl.deletevertexarray(vertexarray); parameters vertexarray a webglvertexarrayobject (vao) object to delete.
... examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
...And 2 more matches
WebGLRenderingContext.drawArrays() - Web APIs
the webglrenderingcontext.drawarrays() method of the webgl api renders primitives from array data.
... syntax void gl.drawarrays(mode, first, count); parameters mode a glenum specifying the type primitive to render.
... first a glint specifying the starting index in the array of vector points.
...And 2 more matches
XRInputSourceArray.entries() - Web APIs
the xrinputsourcearray interface's entries() method returns a javascript iterator which can then be used to iterate over the key/value pairs in the input source array.
... each item in the array is an xrinputsource object.
... syntax let inputsourceiterator = xrinputsourcearray.entries(); for (let entry of xrinputsourcearray.entries()) { /* ...
...And 2 more matches
XRInputSourceArray.values() - Web APIs
the xrinputsourcearray method values() returns a javascript iterator that can walk over the list of xrinputsource objects contained in the array, from first to last.
... syntax xrinputsourcearray.values(); parameters none.
... return value a javascript iterator that can be used to walk through the list of xrinputsource objects in the array, starting with the first entry (at index 0) and proceeding straight through the list.
...And 2 more matches
Array.prototype[@@unscopables] - JavaScript
description the default array properties that are excluded from with bindings are: copywithin() entries() fill() find() findindex() includes() keys() values() see symbol.unscopables for how to set unscopables for your own objects.
... property attributes of array.prototype[@@unscopables] writable no enumerable no configurable yes examples use in with environments the following code works fine in es5 and below.
... however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced.
...And 2 more matches
Array.prototype.toSource() - JavaScript
the tosource() method returns a string representing the source code of the array.
... syntax arr.tosource() return value a string representing the source code of the array.
... description the tosource method returns the following values: for the built-in array object, tosource returns the following string indicating that the source code is not available: function array() { [native code] } for instances of array, tosource returns a string representing the source code.
...And 2 more matches
Array.prototype.unshift() - JavaScript
the unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
... description the unshift method inserts the given values to the beginning of an array-like object.
...this method can be called or applied to objects resembling arrays.
...And 2 more matches
get ArrayBuffer[@@species] - JavaScript
the arraybuffer[@@species] accessor property returns the arraybuffer constructor.
... description the species accessor property returns the default constructor for arraybuffer objects.
... examples species in ordinary objects the species property returns the default constructor function, which is the arraybuffer constructor for arraybuffer objects: arraybuffer[symbol.species]; // function arraybuffer() species in derived objects in a derived collection object (e.g.
...And 2 more matches
SharedArrayBuffer.prototype.slice() - JavaScript
the sharedarraybuffer.prototype.slice() method returns a new sharedarraybuffer whose contents are a copy of this sharedarraybuffer's bytes from begin, inclusive, up to end, exclusive.
... if either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning.
... this method has the same algorithm as array.prototype.slice().
...And 2 more matches
get TypedArray[@@species] - JavaScript
the typedarray[@@species] accessor property returns the constructor of a typed array.
... description the species accessor property returns the default constructor for typed array objects.
... examples species in ordinary objects the species property returns the default constructor function, which is one of the typed array constructors for a given typed array object: int8array[symbol.species]; // function int8array() uint8array[symbol.species]; // function uint8array() float32array[symbol.species]; // function float32array() species in derived objects in a derived collection object (e.g.
...And 2 more matches
TypedArray.prototype.byteLength - JavaScript
the bytelength accessor property represents the length (in bytes) of a typed array.
...the value is established when a typedarray is constructed and cannot be changed.
... if the typedarray is not specifying an byteoffset or a length, the length of the referenced arraybuffer will be returned.
...And 2 more matches
TypedArray.prototype.length - JavaScript
the length accessor property represents the length (in elements) of a typed array.
...the value is established when a typedarray is constructed and cannot be changed.
... if the typedarray is not specifying an byteoffset or a length, the length of the referenced arraybuffer will be returned.
...And 2 more matches
ParallelArray - Archive of obsolete content
the goal of parallelarray was to enable data-parallelism in web applications.
... the higher-order functions available on parallelarray attempted to execute in parallel, though they may fall back to sequential execution if necessary.
... syntax new parallelarray() new parallelarray([element0, element1, ...]) new parallelarray(arraylength, elementalfunction) parallelarray instances properties length reflects the number of elements in the parallelarray.
... methods map reduce scan scatter filter flatten partition get examples using map in parallel var p = new parallelarray([0, 1, 2, 3, 4]); var m = p.map(function (v) { return v + 1; }); ...
JSIdArray
an array of property ids.
... description jsidarray is used to hold ids for enumerated properties associated with an object.
... use js_idarraylength and js_idarrayget to access the property, and js_destroyidarray to free, or use js::autoidarray as a local variable.
... see also mxr id search for jsidarray js_idarraylength js_idarrayget jsproperty js_enumerate js_destroyidarray js::autoidarray ...
ANGLE_instanced_arrays.drawElementsInstancedANGLE() - Web APIs
the angle_instanced_arrays.drawelementsinstancedangle() method of the webgl api renders primitives from array data like the gl.drawelements() method.
... type a glenum specifying the type of the values in the element array buffer.
... possible values are: gl.unsigned_byte gl.unsigned_short when using the oes_element_index_uint extension: gl.unsigned_int offset a glintptr specifying an offset in the element array buffer.
... examples var ext = gl.getextension('angle_instanced_arrays'); ext.drawelementsinstancedangle(gl.points, 2, gl.unsigned_short, 0, 4); specifications specification status comment angle_instanced_arraysthe definition of 'angle_instanced_arrays' in that specification.
HTMLInputElement.mozGetFileNameArray() - Web APIs
the htmlinputelement.mozgetfilenamearray() method returns an array of the names of the files that were selected by the user on an html input element.
... syntax inputelement.mozgetfilenamearray(alength, afilenames); parameters alength if specified, will receive the number of file names in the returned array.
... afilenames is an array into which the file names are placed.
... example var numfiles = 0; var filearray = {}; inputelement.mozgetfilenamearray(numfiles, filearray); ...
HTMLInputElement.mozSetFileNameArray() - Web APIs
the htmlinputelement.mozsetfilenamearray() method sets the names of the files that selected on an html input element.
... syntax inputelement.mozsetfilenamearray(afilenames, alength); parameters afilenames is the array of file names to apply to the element.
... alength is the number of file names in the array.
... example var filearray = {"/foo/bar.txt", "/foo/foosball.txt"}; inputelement.mozsetfilenamearray(filearray, filearray.length); ...
LockedFile.readAsArrayBuffer() - Web APIs
summary the readasarraybuffer method is used to read the content of the lockedfile object and provide the result of that reading as an arraybuffer.
... in many ways, it performs like the filereader.readasarraybuffer() method.
... syntax var request = instanceoflockedfile.readasarraybuffer(size); parameters size a number representing the number of bytes to read in the file.
...in case of success, the request's result is an arraybuffer representing the data that have been read.
WebGLRenderingContext.disableVertexAttribArray() - Web APIs
the webglrenderingcontext.disablevertexattribarray() method of the webgl api turns the generic vertex attribute array off at a given index position.
... syntax void gl.disablevertexattribarray(index); parameters index a gluint specifying the index of the vertex attribute to disable.
... examples gl.disablevertexattribarray(0); specifications specification status comment webgl 1.0the definition of 'disablevertexattribarray' in that specification.
... opengl es 2.0the definition of 'gldisablevertexattribarray' in that specification.
WebGLVertexArrayObject - Web APIs
the webglvertexarrayobject interface is part of the webgl 2 api, represents vertex array objects (vaos) pointing to vertex array data, and provides names for different sets of vertex data.
... when working with webglvertexarrayobject objects, the following methods are useful: webgl2renderingcontext.createvertexarray() webgl2renderingcontext.deletevertexarray() webgl2renderingcontext.isvertexarray() webgl2renderingcontext.bindvertexarray() webgl 1: the oes_vertex_array_object extension allows you to use vertex array objects in a webgl 1 context.
... examples var vao = gl.createvertexarray(); gl.bindvertexarray(vao); // ...
... specifications specification status comment webgl 2.0the definition of 'webglvertexarrayobject' in that specification.
XRInputSourceArray.keys() - Web APIs
the keys() method in the xrinputsourcearray interface returns a javascript iterator which can then be used to iterate over the keys used to reference each item in the array of input sources.
... syntax xrinputsourcearray.keys(); parameters none.
...for each key, the input is retrieved using the index with array notation: xrsession.inputsources[inputidx].
... specifications specification status comment webxr device apithe definition of 'xrinputsourcearray' in that specification.1 working draft xrinputsourcearray interface [1] see iterator-like methods in information contained in a webidl file for information on how an iterable declaration in an interface definition causes entries(), foreach(), keys(), and values() methods to be exposed from objects that implement the interface.
XRInputSourceArray.length - Web APIs
the read-only length property returns an integer value indicating the number of items in the input source list represented by the xrinputsourcearray object.
... syntax let inputsourcecount = xrinputsourcearray.length; value an integer value indicating the number of xrinputsource objects representing webxr input sources are includled in the array.
... least one controller to play super duper shark jump fest 9000.", [ { label: "shop now", url: "https://www.amazon.com/s?k=vr+controllers" }, { label: "quit" handler: quitgame } ]); } here, if length is 0, a hypothetical showalertdialog() function is called with a prompt string explaining the need for a controller, and an array of objects, each describing a button and what should happen when it's clicked.
... specifications specification status comment webxr device apithe definition of 'xrinputsourcearray.length' in that specification.
ArrayBuffer.prototype.byteLength - JavaScript
the bytelength accessor property represents the length of an arraybuffer in bytes.
...the value is established when the array is constructed and cannot be changed.
... this property returns 0 if this arraybuffer has been detached.
... examples using bytelength var buffer = new arraybuffer(8); buffer.bytelength; // 8 specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.prototype.bytelength' in that specification.
ArrayBuffer.isView() - JavaScript
the arraybuffer.isview() method determines whether the passed value is one of the arraybuffer views, such as typed array objects or a dataview.
... syntax arraybuffer.isview(value) parameters value the value to be checked.
... return value true if the given argument is one of the arraybuffer views; otherwise, false.
... examples using isview arraybuffer.isview(); // false arraybuffer.isview([]); // false arraybuffer.isview({}); // false arraybuffer.isview(null); // false arraybuffer.isview(undefined); // false arraybuffer.isview(new arraybuffer(10)); // false arraybuffer.isview(new uint8array()); // true arraybuffer.isview(new float32array()); // true arraybuffer.isview(new int8array(10).subarray(0, 3)); // true const buffer = new arraybuffer(2); const dv = new dataview(buffer); arraybuffer.isview(dv); // true specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.isview' in that specification.
TypedArray.BYTES_PER_ELEMENT - JavaScript
the typedarray.bytes_per_element property represents the size in bytes of each element in an typed array.
... property attributes of typedarray.bytes_per_element writable no enumerable no configurable no description typedarray objects differ from each other in the number of bytes per element and in the way the bytes are interpreted.
... the bytes_per_element constant contains the number of bytes each element in the given typedarray has.
... examples using bytes_per_element int8array.bytes_per_element; // 1 uint8array.bytes_per_element; // 1 uint8clampedarray.bytes_per_element; // 1 int16array.bytes_per_element; // 2 uint16array.bytes_per_element; // 2 int32array.bytes_per_element; // 4 uint32array.bytes_per_element; // 4 float32array.bytes_per_element; // 4 float64array.bytes_per_element; // 8 specifications specification ecmascript (ecma-262)the definition of 'typedarray.bytes_per_element' in that specification.
TypedArray.prototype.buffer - JavaScript
the buffer accessor property represents the arraybuffer referenced by a typedarray at construction time.
...the value is established when the typedarray is constructed and cannot be changed.
... typedarray is one of the typedarray objects.
... examples using the buffer property var buffer = new arraybuffer(8); var uint16 = new uint16array(buffer); uint16.buffer; // arraybuffer { bytelength: 8 } specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.buffer' in that specification.
TypedArray.prototype.byteOffset - JavaScript
the byteoffset accessor property represents the offset (in bytes) of a typed array from the start of its arraybuffer.
...the value is established when a typedarray is constructed and cannot be changed.
... typedarray is one of the typedarray objects.
... examples using the byteoffset property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.byteoffset; // 0 (no offset specified) var uint8 = new uint8array(buffer, 3); uint8.byteoffset; // 3 (as specified when constructing uint8array) specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.byteoffset' in that specification.
TypeError: invalid Array.prototype.sort argument - JavaScript
the javascript exception "invalid array.prototype.sort argument" occurs when the argument of array.prototype.sort() isn't either undefined or a function which compares its operands.
... message typeerror: argument is not a function object (edge) typeerror: invalid array.prototype.sort argument (firefox) error type typeerror what went wrong?
... the argument of array.prototype.sort() is expected to be either undefined or a function which compares its operands.
Array.prototype.entries() - JavaScript
the entries() method returns a new array iterator object that contains the key/value pairs for each index in the array.
... syntax array.entries() return value a new array iterator object.
...ndex and element const a = ['a', 'b', 'c']; for (const [index, element] of a.entries()) console.log(index, element); // 0 'a' // 1 'b' // 2 'c' using a for…of loop var a = ['a', 'b', 'c']; var iterator = a.entries(); for (let e of iterator) { console.log(e); } // [0, 'a'] // [1, 'b'] // [2, 'c'] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.entries' in that specification.
Array.prototype.keys() - JavaScript
the keys() method returns a new array iterator object that contains the keys for each index in the array.
... syntax arr.keys() return value a new array iterator object.
... examples key iterator doesn't ignore holes var arr = ['a', , 'c']; var sparsekeys = object.keys(arr); var densekeys = [...arr.keys()]; console.log(sparsekeys); // ['0', '2'] console.log(densekeys); // [0, 1, 2] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.keys' in that specification.
SharedArrayBuffer.prototype.byteLength - JavaScript
the bytelength accessor property represents the length of an sharedarraybuffer in bytes.
...the value is established when the shared array is constructed and cannot be changed.
... examples using bytelength var sab = new sharedarraybuffer(1024); sab.bytelength; // 1024 specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer.prototype.bytelength' in that specification.
TypedArray.prototype.entries() - JavaScript
the entries() method returns a new array iterator object that contains the key/value pairs for each index in the array.
... syntax arr.entries() return value a new array iterator object.
... examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.entries(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.entries(); console.log(earr.next().value); // [0, 10] console.log(earr.next().value); // [1, 20] console.log(earr.next().value); // [2, 30] console.log(earr.next().value); // [3, 40] console.log(earr.next().value); // [4, 50] specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.entries()' in that specification.
TypedArray.prototype.keys() - JavaScript
the keys() method returns a new array iterator object that contains the keys for each index in the array.
... syntax arr.keys() return value a new array iterator object.
... examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.keys(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.keys(); console.log(earr.next().value); // 0 console.log(earr.next().value); // 1 console.log(earr.next().value); // 2 console.log(earr.next().value); // 3 console.log(earr.next().value); // 4 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.keys()' in that specification.
TypedArray.prototype.values() - JavaScript
the values() method returns a new array iterator object that contains the values for each index in the array.
... syntax arr.values() return value a new array iterator object.
... examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.values(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.values(); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next().value); // 30 console.log(earr.next().value); // 40 console.log(earr.next().value); // 50 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.values()' in that specification.
ANGLE_instanced_arrays.vertexAttribDivisorANGLE() - Web APIs
the angle_instanced_arrays.vertexattribdivisorangle() method of the webgl api modifies the rate at which generic vertex attributes advance when rendering multiple instances of primitives with ext.drawarraysinstancedangle() and ext.drawelementsinstancedangle().
... examples var ext = gl.getextension('angle_instanced_arrays'); ext.vertexattribdivisorangle(0, 2); specifications specification status comment angle_instanced_arraysthe definition of 'angle_instanced_arrays' in that specification.
ArrayBufferView - Web APIs
arraybufferview is a helper type representing any of the following javascript typedarray types: int8array, uint8array, uint8clampedarray, int16array, uint16array, int32array, uint32array, float32array, float64array or dataview.
... specifications specification status comment web idlthe definition of 'arraybufferview' in that specification.
Array.prototype[@@iterator]() - JavaScript
etter + "</li>"; } result alternative iteration var arr = ['a', 'b', 'c', 'd', 'e']; var earr = arr[symbol.iterator](); console.log(earr.next().value); // a console.log(earr.next().value); // b console.log(earr.next().value); // c console.log(earr.next().value); // d console.log(earr.next().value); // e use case for brace notation the use case for this syntax over using the dot notation (array.prototype.values()) is in a case where you don't know what object is going to be ahead of time.
...tprototypeof(it) /* or "symbol.iterator in object.__proto__" or "it[symbol.iterator]" */)) { console.log(it, ' is not an iterable object...'); return; } var iterator = it[symbol.iterator](); // your browser must support for..of loop // and let-scoped variables in for loops // const and var could also be used for (let letter of iterator) { console.log(letter); } } // array logiterable(['a', 'b', 'c']); // a // b // c // string logiterable('abc'); // a // b // c logiterable(123); // 123 " is not an iterable object..." specifications specification ecmascript (ecma-262)the definition of 'array.prototype[@@iterator]()' in that specification.
TypedArray.prototype[@@iterator]() - JavaScript
syntax arr[symbol.iterator]() return value the array iterator function, which is the values() function by default.
... examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of arr) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr[symbol.iterator](); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next().value); // 30 console.log(earr.next().value); // 40 console.log(earr.next().value); // 50 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype[@@iterator]()' in that specification.
XMLHttpRequest.mozResponseArrayBuffer - Web APIs
obsolete since gecko 6 is an arraybuffer response to the request, written as a javascript typed array.
Index - Web APIs
WebAPIIndex
2 angle_instanced_arrays api, reference, webgl, webgl extension the angle_instanced_arrays extension is part of the webgl api and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type.
... 3 angle_instanced_arrays.drawarraysinstancedangle() angle_instanced_arrays, api, method, reference, webgl, webgl extension the angle_instanced_arrays.drawarraysinstancedangle() method of the webgl api renders primitives from array data like the gl.drawarrays() method.
... 4 angle_instanced_arrays.drawelementsinstancedangle() angle_instanced_arrays, api, method, reference, webgl, webgl extension the angle_instanced_arrays.drawelementsinstancedangle() method of the webgl api renders primitives from array data like the gl.drawelements() method.
...And 194 more matches
Indexed collections - JavaScript
this includes arrays and array-like constructs such as array objects and typedarray objects.
... array object an array is an ordered list of values that you refer to with a name and an index.
... for example, consider an array called emp, which contains employees' names indexed by their numerical employee number.
...And 87 more matches
StringView - Archive of obsolete content
the aims of this library are: to create a c-like interface for strings (i.e., an array of character codes — an arraybufferview in javascript) based upon the javascript arraybuffer interface to create a highly extensible library that anyone can extend by adding methods to the object stringview.prototype to create a collection of methods for such string-like objects (since now: stringviews) which work strictly on arrays of numbers rather than on creating new immutable javascript strings to work with unicode encodings other than javascript's default utf-16 domstrings introduction as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when ...
... javascript typed arrays provide a mechanism for accessing raw binary data much more efficiently.
... the stringview constructor is one level above typed arrays.
...And 68 more matches
Index
23 js::autoidarray jsapi reference, reference, référence(2), spidermonkey js::autoidarray takes the ownership of jsidarray, and frees it in destructor by calling js_destroyidarray.
... 25 js::autovaluearray jsapi reference, reference, référence(2), spidermonkey js::autovaluearray<n> holds a rooted array of js::value.
... this is typically used for local variables being passed to function which requires js::handlevaluearray or a pointer to js::value array.
...And 35 more matches
Add to iPhoto
among these are routines for managing cfstring, cfurl, and cfarray objects, among others.
... cfarray the cfarray type is used to create arrays of objects; the objects in the array can be of any type, thanks to a set of callbacks you can provide to handle managing their memory and performing operations such as comparisons.
... the most interesting thing we'll look at here is how to reference the system-provided default callback record, which is exported by core foundation under the name kcftypearraycallbacks.
...And 26 more matches
Working with data
if type is an array type of unspecified length, the following steps are taken: if the value is a size value, a new array of that length is created, with its cells ready to accept values of the same type as those in the specified array.
... this is the same as new arraytype(type.elementtype, value).
... if the type represents a javascript string (that is, an array of jschar characters followed by a null terminator), a copy of that string is created and returned.
...And 24 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
and array, which is a special kind of object.
...so the type diagram looks more like this: number string boolean symbol (new in es2015) object function array date regexp null undefined and there are some built-in error types as well.
... for (var i = 0; i < 5; i++) { // will execute 5 times } javascript also contains two other prominent for loops: for...of for (let value of array) { // do something with value } and for...in: for (let property in object) { // do something with object property } the && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first.
...And 24 more matches
jspage - Archive of obsolete content
l,p){if(typeof n=="string"){var o=this.prototype[n];if((n=o)){return j(this,l,n,p); }}for(var m in n){this.alias(m,n[m],l);}return this;};d.implement=function(m,l,o){if(typeof m=="string"){return j(this,m,l,o);}for(var n in m){j(this,n,m[n],l); }return this;};if(c){d.implement(c);}return d;};native.genericize=function(b,c,a){if((!a||!b[c])&&typeof b.prototype[c]=="function"){b[c]=function(){var d=array.prototype.slice.call(arguments); return b.prototype[c].apply(d.shift(),d);};}};native.implement=function(d,c){for(var b=0,a=d.length;b<a;b++){d[b].implement(c);}};native.typize=function(a,b){if(!a.type){a.type=function(c){return($type(c)===b); };}};(function(){var a={array:array,date:date,function:function,number:number,regexp:regexp,string:string};for(var h in a){new native({name:h,initialize:a[...
...h],protect:true}); }var d={"boolean":boolean,"native":native,object:object};for(var c in d){native.typize(d[c],c);}var f={array:["concat","indexof","join","lastindexof","pop","push","reverse","shift","slice","sort","splice","tostring","unshift","valueof"],string:["charat","charcodeat","concat","indexof","lastindexof","match","replace","search","slice","split","substr","substring","tolowercase","touppercase","valueof"]}; for(var e in f){for(var b=f[e].length;b--;){native.genericize(a[e],f[e][b],true);}}})();var hash=new native({name:"hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getclean()); }for(var b in a){this[b]=a[b];}return this;}});hash.implement({foreach:function(b,c){for(var a in this){if(this.hasownproperty(a)){b.call(c,this[a],a,this); }}},getclean:function(){var b={};f...
...or(var a in this){if(this.hasownproperty(a)){b[a]=this[a];}}return b;},getlength:function(){var b=0;for(var a in this){if(this.hasownproperty(a)){b++; }}return b;}});hash.alias("foreach","each");array.implement({foreach:function(c,d){for(var b=0,a=this.length;b<a;b++){c.call(d,this[b],b,this);}}});array.alias("foreach","each"); function $a(b){if(b.item){var a=b.length,c=new array(a);while(a--){c[a]=b[a];}return c;}return array.prototype.slice.call(b);}function $arguments(a){return function(){return arguments[a]; };}function $chk(a){return !!(a||a===0);}function $clear(a){cleartimeout(a);clearinterval(a);return null;}function $defined(a){return(a!=undefined);}function $each(c,b,d){var a=$type(c); ((a=="arguments"||a=="collection"||a=="array")?array:hash).each(c,b,d);}function $empty(){}function ...
...And 23 more matches
Bytecode Descriptions
this is because the spec insists that array indices are strings, whereas for us they are integers.
...the object must be a singleton plainobject or arrayobject.
... the spec requires that an objectliteral or arrayliteral creates a new object every time it's evaluated, so this instruction must not be used anywhere it might be executed more than once.
...And 23 more matches
WebGL constants - Web APIs
rendering primitives constants passed to webglrenderingcontext.drawelements() or webglrenderingcontext.drawarrays() to specify what kind of primitive to render.
... constant name value description points 0x0000 passed to drawelements or drawarrays to draw single points.
... lines 0x0001 passed to drawelements or drawarrays to draw lines.
...And 22 more matches
OS.File for the main thread
let decoder = new textdecoder(); // this decoder can be reused for several reads let promise = os.file.read("file.txt"); // read the complete file as an array promise = promise.then( function onsuccess(array) { return decoder.decode(array); // convert this array to a text } ); this example requires firefox 18 or a more recent version.
...it uses an atomic write to ensure that the file is not modified if, for some reason, the write cannot complete (typically because the computer is turned off, the battery runs out, or the application is stopped.) let encoder = new textencoder(); // this encoder can be reused for several writes let array = encoder.encode("this is some text"); // convert the text to an array let promise = os.file.writeatomic("file.txt", array, // write the array atomically to "file.txt", using as temporary {tmppath: "file.txt.tmp"}); // buffer "file.txt.tmp".
... the following variant does the same thing but will fail if "file.txt" already exists: let encoder = new textencoder(); // this encoder can be reused for several writes let array = encoder.encode("this is some text"); // convert the text to an array let promise = os.file.writeatomic("file.txt", array, // write the array atomically to "file.txt", using as temporary {tmppath: "file.txt.tmp", nooverwrite: true}); // buffer "file.txt.tmp".
...And 21 more matches
Function.prototype.apply() - JavaScript
the apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).
... syntax func.apply(thisarg, [ argsarray]) parameters thisarg the value of this provided for the call to func.
... argsarray optional an array-like object, specifying the arguments with which func should be called, or null or undefined if no arguments should be provided to the function.
...And 21 more matches
Mozilla DOM Hacking Guide
other browsers allow the history object to be used like an array, e.g.
...the behavior "act as an array" cannot be reflected in the idl itself.
... fortunately, xpconnect provides us with a way to make our class available as an array in javascript.
...And 20 more matches
Shell global objects
variables scriptargs an array that contains arguments passed to js shell.
... getsharedarraybuffer() retrieve the sharedarraybuffer object from the cross-worker mailbox.
...getsharedarraybuffer performs an ordering memory barrier.
...And 20 more matches
String.prototype.split() - JavaScript
the split() method divides a string into an ordered list of substrings, puts these substrings into an array, and returns the array.
... if separator is omitted or does not occur in str, the returned array contains one element consisting of the entire string.
...zero length) string, which appears at the first (or last) position of the returned array.
...And 20 more matches
WebIDL bindings
o* owningnonnull<foo> interface: nullable foo* already_addrefed<foo> foo* refptr<foo> long int32_t int32_t int32_t long long int64_t int64_t int64_t object js::handle<jsobject*> js::mutablehandle<jsobject*> jsobject* octet uint8_t uint8_t uint8_t sequence const sequence<t>& nstarray<t>& (outparam) short int16_t int16_t int16_t unrestricted double double double double unrestricted float float float float unsigned long uint32_t uint32_t uint32_t unsigned long long uint64_t uint64_t uint64_t unsigned short uint16_t uint16_t uint16_t usvstring const nsastri...
..."spidermonkey" interfaces are used to represent objects that are implemented natively by the javascript engine (e.g., typed arrays).
... "spidermonkey" interfaces typed array, array buffer, and array buffer view arguments are represented by the objects in typedarray.h.
...And 18 more matches
WebGLRenderingContext.vertexAttribPointer() - Web APIs
the webglrenderingcontext.vertexattribpointer() method of the webgl api binds the buffer currently bound to gl.array_buffer to a generic vertex attribute of the current vertex buffer object and specifies its layout.
... type a glenum specifying the data type of each component in the array.
... offset a glintptr specifying an offset in bytes of the first component in the vertex attribute array.
...And 18 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
we'll take the tasks information from the markup and store it in a todos array.
...find the <h2> heading with an id of list-heading and replace the hardcoded number of active and completed tasks with dynamic expressions: <h2 id="list-heading">{completedtodos} out of {totaltodos} items completed</h2> go to the app, and you should see the "2 out of 3 items completed" message as before, but this time the information is coming from the todos array.
... to prove it, go to that array, and try changing some of the todo object's completed property values, and even add a new todo object.
...And 17 more matches
JNI.jsm
afullyqualifiedname a sig of a typed array or the name of the class that would be used in a signature, but without the surrounding l and ;.
... if it is the sig of a typed array such as '[i' then adeclares must not be declared.
... see the section "working with arrays" to see how this is used to create typed arrays.
...And 17 more matches
Index
MozillaTechXPCOMIndex
23 components.interfacesbyid xpcom:language bindings, xpconnect components.interfacesbyid is a read-only array of classes indexed by iid.
...hashtables may seem like arrays, but there are important differences: 114 how to build an xpcom component in javascript add-ons, extensions, javascript, tutorial, xpcom if you are looking for add-on sdk solution for xpcom javascript components then check out platform/xpcom module first.
... 120 xpcom array guide guide, needscontent, needsmarkupwork, xpcom mozilla has many array classes because each array is optimized for a particular usage pattern.
...And 16 more matches
Multiprocess on Windows
the required steps are as follows: ensure that you generate typelibs for all of your com interfaces; ensure that those interfaces are registered; register any outparams that consist of arrays of interfaces.
... registering outparams that consist of arrays of interfaces recall that one of the limitations of typelibs is that their metadata isn't as rich as oicf metadata.
...without the support for length_is and size_is annotations, the interceptor cannot tell the difference between a scalar outparam and an array outparam.
...And 15 more matches
nsILoginManagerStorage
method overview void addlogin(in nsilogininfo alogin); unsigned long countlogins(in astring ahostname, in astring aactionurl, in astring ahttprealm); void findlogins(out unsigned long count, in astring ahostname, in astring aactionurl, in astring ahttprealm, [retval, array, size_is(count)] out nsilogininfo logins); void getalldisabledhosts([optional] out unsigned long count, [retval, array, size_is(count)] out wstring hostnames); void getallencryptedlogins([optional] out unsigned long count, [retval, array, size_is(count)] out nsilogininfo logins); void getalllogins([optional] out unsigned long count, [retval, array, size_is(count)] out nsilogininfo logins);...
... boolean getloginsavingenabled(in astring ahost); void init(); void initwithfile(in nsifile ainputfile, in nsifile aoutputfile); void modifylogin(in nsilogininfo oldlogin, in nsisupports newlogindata); void removealllogins(); void removelogin(in nsilogininfo alogin); void searchlogins(out unsigned long count, in nsipropertybag matchdata, [retval, array, size_is(count)] out nsilogininfo logins); void setloginsavingenabled(in astring ahost, in boolean isenabled); attributes attribute type description uibusy boolean true when a master password prompt is being shown.
...void findlogins( out unsigned long count, in astring ahostname, in astring aactionurl, in astring ahttprealm, [retval, array, size_is(count)] out nsilogininfo logins ); parameters count return in this parameter the number of matching logins found by the search.
...And 15 more matches
nsIMsgFolder
inherits from: nsisupports method overview void startfolderloading(); void endfolderloading(); void updatefolder(in nsimsgwindow awindow); nsimsgfilterlist getfilterlist(in nsimsgwindow msgwindow); void setfilterlist(in nsimsgfilterlist filterlist); void forcedbclosed(); void delete(); void deletesubfolders(in nsisupportsarray folders, in nsimsgwindow msgwindow); void propagatedelete(in nsimsgfolder folder, in boolean deletestorage,in nsimsgwindow msgwindow); void recursivedelete(in boolean deletestorage, in nsimsgwindow msgwindow); void createsubfolder(in astring foldername, in nsimsgwindow msgwindow); nsimsgfolder addsubfolder(in astring foldername); void createstorageifmi...
...ssing(in nsiurllistener urllistener); void compact(in nsiurllistener alistener, in nsimsgwindow amsgwindow); void compactall(in nsiurllistener alistener, innsimsgwindow amsgwindow,in nsisupportsarray afolderarray, in boolean acompactofflinealso,in nsisupportsarray aofflinefolderarray); void compactallofflinestores(in nsimsgwindow amsgwindow,in nsisupportsarray aofflinefolderarray); void emptytrash(in nsimsgwindow amsgwindow, in nsiurllistener alistener); void rename(in astring name, in nsimsgwindow msgwindow); void renamesubfolders( in nsimsgwindow msgwindow, in nsimsgfolder oldfolder); astring generateuniquesubfoldername(in astring prefix,in nsimsgfolder otherfolder); void updatesummarytotals(in boolean force); vo...
...flag(in unsigned long flag); void clearflag(in unsigned long flag); boolean getflag(in unsigned long flag); void toggleflag(in unsigned long flag); void onflagchange(in unsigned long flag); void setprefflag(); nsimsgfolder getfolderswithflag(in unsigned long flags, in unsigned long resultsize, out unsigned long numfolders); nsisupportsarray getallfolderswithflag(in unsigned long aflag); void getexpansionarray(in nsisupportsarray expansionarray); acstring geturiformsg(in nsimsgdbhdr msghdr); void deletemessages(in nsisupportsarray messages,in nsimsgwindow msgwindow, in boolean deletestorage, in boolean ismove, in nsimsgcopyservicelistener listener, in boolean allowundo); void copymessages(in nsimsg...
...And 15 more matches
context-menu - Archive of obsolete content
matchpattern is a match pattern string or an array of match pattern strings.
... when matchpattern is an array, the context occurs when the menu is invoked on a page whose url matches any of the patterns.
... array an array of any of the other types.
...And 14 more matches
Tree View Details - Archive of obsolete content
example of hierarchical custom view let's put this together into a simple example that takes an array and constructs a tree from it.
...first we'll define two structures to hold the data for the tree, the first will hold a map between parents and the children they contain, and the second will hold an array of the visible items.
... var treeview = { childdata : { solids: ["silver", "gold", "lead"], liquids: ["mercury"], gases: ["helium", "nitrogen"] }, visibledata : [ ["solids", true, false], ["liquids", true, false], ["gases", true, false] ], }; the childdata structure holds an array of the children for each of the three parent nodes.
...And 14 more matches
Places utilities for JavaScript
eislivemarkcontainer(nsinavhistoryresultnode anode); obsolete since gecko 21 boolean nodeislivemarkitem(nsinavhistoryresultnode anode); obsolete since gecko 21 boolean isreadonlyfolder(nsinavhistoryresultnode anode); int getindexofnode(nsinavhistoryresultnode anode); string wrapnode(nsinavhistoryresultnode anode, string atype, nsiuri aoverrideuri); array unwrapnodes(string blob, string atype); nsitransaction maketransaction(string data, string type, nsinavhistoryresultnode container, int index, boolean copy); nsinavhistoryresult getfoldercontents(int afolderid, boolean aexcludeitems, boolean aexpandqueries); boolean showaddbookmarkui(nsiuri auri, string atitle, string adescription, int adefaultinsertionpoint, boolean as...
...string akeyword, string apostdata); boolean showaddlivemarkui(nsiuri afeeduri, nsiuri asiteuri, string atitle, string adescription, int adefaultinsertionpoint, boolean ashowpicker); boolean showminimaladdlivemarkui(nsiuri afeeduri, nsiuri asiteuri, string atitle, string adescription, int adefaultinsertionpoint, boolean ashowpicker); boolean showminimaladdmultibookmarkui(array nsiuri aurilist); boolean showbookmarkproperties(int aid); boolean showfolderproperties(int aid); boolean showaddfolderui(string atitle, int adefaultinsertionpoint, boolean ashowpicker); array object getannotationsforuri(nsiuri auri); array object getannotationsforitem(int aitemid); void setannotationsforuri(nsiuri auri, object aannos); ...
...ed(string aurl); void markpageasfollowedbookmark(string aurl); boolean checkurlsecurity(nsinavhistoryresultnode aurinode); string getquerystringforfolder(int afolderid); string getdescriptionfromdocument(nsidomdocument doc); string setpostdataforbookmark(int aboomarkid, string apostdata); string getpostdataforbookmark(int aboomarkid); array string geturlandpostdataforkeyword(string akeyword); string getitemdescription(int aitemid); nsinavhistoryresultnode getmostrecentbookmarkforuri(nsiuri auri); nsinavhistoryresultnode getmostrecentfolderforfeeduri(nsiuri auri); nsinavhistoryresultnode geturlsforcontainernode(nsinavhistoryresultnode anode); void opencontainernodeintabs(nsinavhistoryresul...
...And 14 more matches
nsIMessenger
identity, in astring amsgfilename); void openattachment(in acstring contenttpe, in acstring url, in acstring displayname, in acstring messageuri, in boolean isexternalattachment); void saveattachment(in acstring contenttpe, in acstring url, in acstring displayname, in acstring messageuri, in boolean isexternalattachment); void saveallattachments(in unsigned long count, [array, size_is(count)] in string contenttypearray, [array, size_is(count)] in string urlarray, [array, size_is(count)] in string displaynamearray, [array, size_is(count)] in string messageuriarray); void saveattachmenttofile(in nsifile afile, in acstring aurl, in acstring amessageuri, in acstring acontenttype, in nsiurllistener alistener); void detachattachment(in string contenttpe, i...
...n string url, in string displayname, in string messageuri, in boolean savefirst, [optional] in boolean withoutwarning); void detachallattachments(in unsigned long count, [array, size_is(count)] in string contenttypearray, [array, size_is(count)] in string urlarray, [array, size_is(count)] in string displaynamearray, [array, size_is(count)] in string messageuriarray, in boolean savefirst, [optional] in boolean withoutwarning); nsilocalfile saveattachmenttofolder(in acstring contenttype, in acstring url, in acstring displayname, in acstring messageuri, in nsilocalfile adestfolder); nsimsgmessageservice messageservicefromuri(in acstring auri); nsimsgdbhdr msghdrfromuri(in acstring auri); acstring getmsguriatnavigatepos(in long apos); acstring g...
...etfolderuriatnavigatepos(in long apos); void getnavigatehistory(out unsigned long acurpos, out unsigned long acount, [array, size_is(acount)] out string ahistory); note: prior to gecko 8.0, all references to nsidomwindow used in this interface were nsidomwindow.
...And 14 more matches
Spread syntax (...) - JavaScript
spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
... syntax for function calls: myfunction(...iterableobj); for array literals or strings: [...iterableobj, '4', 'five', 6]; for object literals (new in ecmascript 2018): let objclone = { ...obj }; rest syntax (parameters) rest syntax looks exactly like spread syntax.
...spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element.
...And 14 more matches
page-mod - Archive of obsolete content
mozilla.org", contentscript: 'window.alert("page matches ruleset");' }); you can modify the document in your script: var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscript: 'document.body.innerhtml = ' + ' "<h1>page matches ruleset</h1>";' }); you can supply the content script(s) in one of two ways: as a string literal, or an array of string literals, assigned to the contentscript option, as above as separate files supplied in your add-on's "data" directory.
...list of workers attached to a page-mod: var workers = []; var pagemod = require("sdk/page-mod").pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: data.url('pagemod.js'), onattach: function(worker) { workers.push(worker); } }); you can remove workers when they are no longer valid by listening to detach: var workers = []; function detachworker(worker, workerarray) { var index = workerarray.indexof(worker); if(index != -1) { workerarray.splice(index, 1); } } var pagemod = require("sdk/page-mod").pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: data.url('pagemod.js'), onattach: function(worker) { workers.push(worker); worker.on('detach', function () { detachworker(this, workers); }); } }); clea...
... parameters options : object required options: name: include type: string, regexp, or array of (string or regexp) a match pattern string or an array of match pattern strings.
...And 13 more matches
places/bookmarks - Archive of obsolete content
th properties // such as `updated` and `id`), as well as the initial input // item as `inputitem` console.log(saved.title === inputitem.title); // true console.log(saved !== inputitem); // true console.log(inputitem === bookmark); // true }).on("end", function (saveditems, inputitems) { // similar to "data" events, except "end" is an aggregate of // all progress events, with ordered arrays as `saveditems` // and `inputitems` }); creating several bookmarks with a new group let { bookmark, group, save } = require("sdk/places/bookmarks"); let group = group({ title: "guitars" }); let bookmarks = [ bookmark({ title: "ran", url: "http://ranguitars.com", group: group }), bookmark({ title: "ibanez", url: "http://ibanez.com", group: group }), bookmark({ title: "esp", url: "http:...
...//espguitars.com", group: group }) ]; // save `bookmarks` array -- notice we don't have `group` in the array, // although it needs to be saved since all bookmarks are children // of `group`.
... save(bookmarks).on("data", function (saved, input) { // a data event is called once for each item saved, as well // as implicit items, like `group` console.log(input === group || ~bookmarks.indexof(input)); // true }).on("end", function (saves, inputs) { // like the previous example, the "end" event returns an // array of all of our updated saves.
...And 13 more matches
AddonManager
callbacks installcallback() a callback that is passed a single addoninstall void installcallback( in addoninstall install ) parameters install the addoninstall passed back from the asynchronous request installlistcallback() a callback that is passed an array of addoninstalls void installlistcallback( in addoninstall installs[] ) parameters installs the array of addoninstalls passed back from the asynchronous request addoncallback() a callback that is passed a single addon void addoncallback( in addon addon ) parameters addon the addon passed back from the asynchronous request.
... addonlistcallback() a callback that is passed an array of addons void addonlistcallback( in addon addons[] ) parameters addons the array of addons passed back from the asynchronous request constants addoninstall states constant description state_available an install that is waiting to be started.
... getstartupchanges() returns an array of add-on ids that changed for a given startup change type.
...And 13 more matches
JIT Optimization Strategies
for example, in the following code: var constants = {}; constants.n = 100; function testarray(array) { for (var i = 0; i < array.length; i++) { if (array[i] > constants.n) return true; } return false; } will have the loop compiled into the following when testarray gets hot.
... for (var i = 0; i < array.length; i++) { if (array[i] > 100) return true; } when this optimization is successful, property access is eliminated entirely and replaced with an inline constant.
... getelement getelem_typedobject attempts to optimized element accesses on array typed objects.
...And 13 more matches
nsILoginManager
rch(in astring asearchstring, in nsiautocompleteresult apreviousresult, in nsidomhtmlinputelement aelement); unsigned long countlogins(in astring ahostname, in astring aactionurl, in astring ahttprealm); boolean fillform(in nsidomhtmlformelement aform); void findlogins(out unsigned long count, in astring ahostname, in astring aactionurl, in astring ahttprealm, [retval, array, size_is(count)] out nsilogininfo logins); void getalldisabledhosts([optional] out unsigned long count, [retval, array, size_is(count)] out wstring hostnames); void getalllogins([optional] out unsigned long count, [retval, array, size_is(count)] out nsilogininfo logins); boolean getloginsavingenabled(in astring ahost); void modifylogin(in nsilogininfo oldlogin,...
... in nsisupports newlogindata); void removealllogins(); void removelogin(in nsilogininfo alogin); void searchlogins(out unsigned long count, in nsipropertybag matchdata, [retval, array, size_is(count)] out nsilogininfo logins); void setloginsavingenabled(in astring ahost, in boolean isenabled); methods addlogin() stores a new login in the login manager.
... void findlogins( out unsigned long count, in astring ahostname, in astring aactionurl, in astring ahttprealm, [retval, array, size_is(count)] out nsilogininfo logins ); parameters count the number of elements in the returned array.
...And 13 more matches
SubtleCrypto.unwrapKey() - Web APIs
wrappedkey is an arraybuffer containing the wrapped key in the given format.
... keyusages is an array indicating what can be done with the key.
... possible values of the array are: encrypt: the key may be used to encrypt messages.
...And 13 more matches
Grammar and types - JavaScript
for example, the following code executes the function myfunction because the myarray element is undefined: var myarray = []; if (!myarray[0]) myfunction(); the undefined value converts to nan when used in numeric context.
... const my_object = {'key': 'value'}; my_object.key = 'othervalue'; also, the contents of an array are not protected, so the following statement is executed without problems.
... const my_array = ['html','css']; my_array.push('javascript'); console.log(my_array); //logs ['html','css','javascript']; data structures and types data types the latest ecmascript standard defines eight data types: seven data types that are primitives: boolean.
...And 13 more matches
Index - Archive of obsolete content
124 util/array helper functions for working with arrays.
... 2003 archived javascript reference archive, javascript, obsolete, overview obsolete javascript features and unmaintained docs 2004 array comprehensions javascript, language feature, non-standard, obsolete, operator, reference the array comprehension syntax was a javascript expression which allowed you to quickly assemble a new array based on an existing one.
... 2005 array.observe() array, javascript, method, obsolete the array.observe() method was used for asynchronously observing changes to arrays, similar to object.observe() for objects.
...And 12 more matches
JS::AutoVectorRooter
this article covers features introduced in spidermonkey 17 base class that roots an internal variable-size array of type t.
... syntax js::autovectorrooter(jscontext* cx); methods method description size_t length() const returns the length of the array.
... bool empty() const determines if the array is empty (length is zero).
...And 12 more matches
nsIMsgDatabase
g size); nsimsgdbhdr getmsghdrforkey(in nsmsgkey key); nsimsgdbhdr getmsghdrformessageid(in string messageid); boolean containskey(in nsmsgkey key); nsimsgdbhdr createnewhdr(in nsmsgkey key); void addnewhdrtodb(in nsimsgdbhdr newhdr, in boolean notify); nsimsgdbhdr copyhdrfromexistinghdr(in nsmsgkey key, in nsimsgdbhdr existinghdr, in boolean addhdrtodb); void listallkeys(in nsmsgkeyarrayref outputkeys); native code only!
...stigator); void markreplied(in nsmsgkey key, in boolean breplied, in nsidbchangelistener instigator); void markforwarded(in nsmsgkey key, in boolean bforwarded, in nsidbchangelistener instigator); void markhasattachments(in nsmsgkey key, in boolean bhasattachments, in nsidbchangelistener instigator); void markthreadread(in nsimsgthread thread, in nsidbchangelistener instigator, in nsmsgkeyarrayptr thosemarked); native code only!
...readwatched(in nsimsgthread thread, in nsmsgkey threadkey, in boolean bwatched, in nsidbchangelistener instigator); void markheaderkilled(in nsimsgdbhdr msg, in boolean bignored, in nsidbchangelistener instigator); boolean isread(in nsmsgkey key); boolean isignored(in nsmsgkey key); boolean ismarked(in nsmsgkey key); boolean hasattachments(in nsmsgkey key); void markallread(in nsmsgkeyarrayptr thosemarked); native code only!
...And 12 more matches
SubtleCrypto.importKey() - Web APIs
keydata is an arraybuffer, a typedarray, a dataview, or a jsonwebkey object containing the key in the given format.
... keyusages is an array indicating what can be done with the key.
... possible array values are: encrypt: the key may be used to encrypt messages.
...And 12 more matches
React interactivity: Events and state - Learn web development
usestate() returns these two things, so we are using array destructuring to capture them both in separate variables.
...there’s one problem however: we can’t just pass the name argument of addtask() into settasks, because tasks is an array of objects and name is a string.
... if we tried to do this, the array would be replaced with the string.
...And 11 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
we will learn how to deal with reactivity issues related to updating objects and arrays.
... reactivity gotchas: updating objects and arrays to see what's happening we can log the todos array from the checkalltodos() function to the console.
... you'll notice that the array is successfully updated every time you press the button (the todo objects' completed properties are toggled between true and false), but svelte is not aware of that.
...And 11 more matches
XPCOMUtils.jsm
create an array of component constructors.
...}, // [optional] an array of categories to register this component in.
... _xpcom_categories: [{ // each object in the array specifies the parameters to pass to // nsicategorymanager.addcategoryentry().
...And 11 more matches
AudioWorkletProcessor.process - Web APIs
therefore, you must always check the size of the sample array rather than assuming a particular size.
... syntax var isactivelyprocessing = audioworkletprocessor.process(inputs, outputs, parameters); parameters inputs an array of inputs connected to the node, each item of which is, in turn, an array of channels.
... each channel is a float32array containing 128 samples.
...And 11 more matches
Background audio processing using AudioWorklet - Web APIs
fundamentally, the audio for a single audio channel (such as the left speaker or the subwoofer, for example) is represented as a float32array whose values are the individual audio samples.
... by specification, each block of audio your process() function receives contains 128 frames (that is, 128 samples for each channel), but it is planned that this value will change in the future, and may in fact vary depending on circumstances, so you should always check the array's length rather than assuming a particular size.
...so each input is, in turn, an array of channels.
...And 11 more matches
Visualizations with Web Audio API - Web APIs
these methods copy data into a specified array, so you need to create a new array to receive the data before invoking one.
... the first one produces 32-bit floating point numbers, and the second and third ones produce 8-bit unsigned integers, therefore a standard javascript array won't do — you need to use a float32array or uint8array array, depending on what data you are handling.
...we return the analysernode.frequencybincount value, which is half the fft, then call uint8array() with the frequencybincount as its length argument — this is how many data points we will be collecting, for that fft size.
...And 11 more matches
Atomics - JavaScript
they are used with sharedarraybuffer and arraybuffer objects.
... static methods atomics.add() adds the provided value to the existing value at the specified index of the array.
... atomics.and() computes a bitwise and on the value at the specified index of the array with the provided value.
...And 11 more matches
util/collection - Archive of obsolete content
usage a collection is ordered, like an array, but its items are unique, like a set.
... globals constructors collection([array]) creates a new collection.
... the collection is backed by an array.
...And 10 more matches
WebRequest.jsm
opt_extrainfospec array of string the optional opt_extrainfospec argument lets you pass extra instructions for the handling of events.
... types array of strings.
... an array of resource types.
...And 10 more matches
Parser API
interface arrayexpression <: expression { type: "arrayexpression"; elements: [ expression | null ]; } an array expression.
... interface comprehensionexpression <: expression { type: "comprehensionexpression"; body: expression; blocks: [ comprehensionblock | comprehensionif ]; filter: expression | null; } an array comprehension.
... the blocks array corresponds to the sequence of for and for each blocks.
...And 10 more matches
IAccessible2
extendedstates() returns the extended states (array of strings).
...refer to @ref _arrayconsideration "special consideration when using arrays" for more details.
... extendedstates this array is allocated by the server.
...And 10 more matches
nsIProcess
to create an instance, use: var process = components.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess); method overview void init(in nsifile executable); void initwithpid(in unsigned long pid); obsolete since gecko 1.9.2 void kill(); void run(in boolean blocking, [array, size_is(count)] in string args, in unsigned long count); void runasync([array, size_is(count)] in string args, in unsigned long count, [optional] in nsiobserver observer, [optional] in boolean holdweak); void runw(in boolean blocking, [array, size_is(count)] in wstring args, in unsigned long count); void runwasync([array, size_is(count)] in wstring args, in unsigned ...
... void run( in boolean blocking, [array, size_is(count)] in string args, in unsigned long count ); parameters blocking if true, this method will block until the process terminates; if false, the method returns immediately.
... args an array of count arguments, using the native character set, to be passed to the executable on its command line.
...And 10 more matches
TextEncoder.prototype.encodeInto() - Web APIs
the textencoder.prototype.encodeinto() method takes a usvstring to encode and a destination uint8array to put resulting utf-8 encoded text into, and returns a dictionary object indicating the progress of the encoding.
... syntax b1 = encoder.encodeinto(string, uint8array); parameters string is a usvstring containing the text to encode.
... uint8array is a uint8array object instance to place the resulting utf-8 encoded text into.
...And 10 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
*/ ) { var aargs = array.prototype.slice.call(arguments, 2); return __nativest__(vcallback instanceof function ?
...*/ ) { var aargs = array.prototype.slice.call(arguments, 2); return __nativesi__(vcallback instanceof function ?
... see the following example: myarray = ['zero', 'one', 'two']; myarray.mymethod = function (sproperty) { alert(arguments.length > 0 ?
...And 10 more matches
Dehydra Object Reference - Archive of obsolete content
.attributes array of objects attributes of the type or declaration.
... each member of the array has the following properties: { name: string, value: string or number, if applicable } see an example on enforcing final classes.
... .assign array of variable objects this variable is the lhs of an assignment.
...And 9 more matches
Working with JSON - Learn web development
you can include the same basic data types inside json as you can in a standard javascript object — strings, numbers, arrays, booleans, and other object literals.
...for example: superheroes.hometown superheroes['active'] to access data further down the hierarchy, you simply have to chain the required property names and array indexes together.
... members contains an array populated by objects.
...And 9 more matches
CustomizableUI.jsm
void removewidgetfromarea(awidgetid); void movewidgetwithinarea(awidgetid, aposition); void ensurewidgetplacedinwindow(awidgetid, awindow); void beginbatchupdate(); void endbatchupdate(aforcedirty); widgetgroupwrapper createwidget(awidgetspecification); void destroywidget(awidgetid); widgetgroupwrapper getwidget(awidgetid); array getunusedwidgets(awindow); array getwidgetidsinarea(aareaid); array getwidgetsinarea(aareaid); string getareatype(aareaid); domelement getcustomizetargetforarea(aareaid, awindow); void reset(); void undoreset(); void removeextratoolbar(); object getplacementofwidget(awidgetid); bool iswidgetremovable(awidgetnodeorwid...
... defaultplacements an array of widget ids making up the default contents of the area.
... getunusedwidgets() get an array of widget wrappers for all the widgets which are currently not in any area (so which are in the palette).
...And 9 more matches
mozIStorageStatement
inherits from: mozistoragevaluearray last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) for an introduction on how to use this interface, see the storage overview document.
...g getparametername(in unsigned long aparamindex); unsigned long getparameterindex(in autf8string aname); autf8string getcolumnname(in unsigned long acolumnindex); unsigned long getcolumnindex(in autf8string aname); void reset(); astring escapestringforlike(in astring avalue, in wchar aescapechar); void bindparameters(in mozistoragebindingparamsarray aparameters); mozistoragebindingparamsarray newbindingparamsarray(); void bindutf8stringparameter(in unsigned long aparamindex, in autf8string avalue); void bindstringparameter(in unsigned long aparamindex, in astring avalue); void binddoubleparameter(in unsigned long aparamindex, in double avalue); void bindint32parameter(in unsigned long aparaminde...
...x, in long avalue); void bindint64parameter(in unsigned long aparamindex, in long long avalue); void bindnullparameter(in unsigned long aparamindex); void bindblobparameter(in unsigned long aparamindex, [array,const,size_is(avaluesize)] in octet avalue, in unsigned long avaluesize); mozistoragependingstatement executeasync(mozistoragestatementcallback acallback); boolean executestep(); boolean step(); void execute(); attributes attribute type description columncount unsigned long number of columns returned.
...And 9 more matches
nsIAccessibleTable
tcolumnatindex in gecko 1.9.2 void getrowandcolumnindicesat(in long cellindex, out long rowindex, out long columnindex); astring getrowdescription(in long rowindex); long getrowextentat(in long row, in long column); long getrowindexat(in long cellindex); note: renamed from getrowatindex in gecko 1.9.2 void getselectedcellindices(out unsigned long cellsarraysize, [retval, array, size_is(cellsarraysize)] out long cellsarray); note: renamed from getselectedcells in gecko 1.9.2 void getselectedcolumnindices(out unsigned long columnsarraysize, [retval, array, size_is(columnsarraysize)] out long columnsarray); note: renamed from getselectedcolumns in gecko 1.9.2 void getselectedrowindices(out unsigned long rowsarraysize, [retval, array, ...
...size_is(rowsarraysize)] out long rowsarray); note: renamed from getselectedrows in gecko 1.9.2 boolean iscellselected(in long rowindex, in long columnindex); boolean iscolumnselected(in long columnindex); boolean isprobablyforlayout(); boolean isrowselected(in long rowindex); void selectcolumn(in long columnindex); void selectrow(in long rowindex); void unselectcolumn(in long columnindex); void unselectrow(in long rowindex); attributes attribute type description caption nsiaccessible the caption accessible for the table.
... note: renamed from selectedcellscount in gecko 1.9.2 selectedcells nsiarray an array of selected cells.
...And 9 more matches
nsIAnnotationService
signed short aexpiration); void setpageannotationdouble(in nsiuri auri, in autf8string aname, in double avalue, in long aflags, in unsigned short aexpiration); void setitemannotationdouble(in long long aitemid, in autf8string aname, in double avalue, in long aflags, in unsigned short aexpiration); void setpageannotationbinary(in nsiuri auri, in autf8string aname,[const, array, size_is(adatalen)] in octet adata, in unsigned long adatalen, in autf8string amimetype, in long aflags, in unsigned short aexpiration); void setitemannotationbinary(in long long aitemid, in autf8string aname,[const, array, size_is(adatalen)] in octet adata, in unsigned long adatalen, in autf8string amimetype, in long aflags, in unsigned short aexpiration); nsivariant getpageann...
... long long getpageannotationint64(in nsiuri auri, in autf8string aname); long long getitemannotationint64(in long long aitemid, in autf8string aname); double getpageannotationdouble(in nsiuri auri, in autf8string aname); double getitemannotationdouble(in long long aitemid, in autf8string aname); void getpageannotationbinary(in nsiuri auri, in autf8string aname,[array, size_is(adatalen)] out octet adata, out unsigned long adatalen, out autf8string amimetype); void getitemannotationbinary(in long long aitemid, in autf8string aname,[array, size_is(adatalen)] out octet adata, out unsigned long adatalen, out autf8string amimetype); void getpageannotationinfo(in nsiuri auri, in autf8string aname, out print32 aflags, out unsigned short aexpiration,...
..., in autf8string aname, out long aflags, out unsigned short aexpiration, out autf8string amimetype, out unsigned short atype); pruint16 getpageannotationtype(in nsiuri auri, in autf8string aname); pruint16 getitemannotationtype(in long long aitemid, in autf8string aname); void getpageswithannotation(in autf8string name, [optional] out unsigned long resultcount, [retval, array, size_is(resultcount)] out nsiuri results); void getitemswithannotation(in autf8string name, [optional] out unsigned long resultcount, [retval, array, size_is(resultcount)] out long long results); void getpageannotationnames(in nsiuri auri, [optional] out unsigned long count, [retval, array, size_is(count)] out nsivariant result); void getitemannotationnames(in long lon...
...And 9 more matches
nsIVariant
nsresult getasarray(out pruint16 type, out nsiid iid, out pruint32 count, out voidptr ptr); violates the xpcom interface guidelines astring getasastring(); native code only!
...arrays and interface pointers cannot be converted to a string.
... violates the xpcom interface guidelines getasarray() nsresult getasarray( out pruint16 type, out nsiid iid, out pruint32 count, out voidptr ptr ); parameters type the type of the array elements.
...And 9 more matches
Debugger.Script - Firefox Developer Tools
getalloffsets() if the instance refers to a jsscript, return an arrayl describing the relationship between bytecode instruction offsets and source code positions in this script.l is sparse, and indexed by source line number.
...if there is code forline, then l[line] is an array of offsets of byte code instructions that are entry points to that line.
... a[i] = i*i; calling getalloffsets() on that code might yield an array like this: [[0], [5, 20], , [10]] this array indicates that: the first line’s code starts at offset 0 in the script; the for statement head has two entry points at offsets 5 and 20 (for the initialization, which is performed only once, and the loop test, which is performed at the start of each iteration); the third line has no code; and the fourth line begins at offset 10.
...And 9 more matches
Debugger - Firefox Developer Tools
arguments an array of strings, representing the arguments substituted into the error message.
... getdebuggees() return an array of distinct debugger.object instances whose referents are all the global objects this debugger instance is debugging.
... since debugger instances don’t hold strong references to their debuggee globals, if a debuggee global is otherwise unreachable, it may be dropped at any moment from the array this method returns.
...And 9 more matches
WebGL2RenderingContext - Web APIs
webgl2renderingcontext.getbuffersubdata() reads data from a buffer and writes them to an arraybuffer or sharedarraybuffer.
... webgl2renderingcontext.texstorage3d() specifies all levels of a three-dimensional texture or two-dimensional array texture.
... webgl2renderingcontext.vertexattribipointer() specifies integer data formats and locations of vertex attributes in a vertex attributes array.
...And 9 more matches
Destructuring assignment - JavaScript
the destructuring assignment syntax is a javascript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
...(b); // 20 [a, b, ...rest] = [10, 20, 30, 40, 50]; console.log(a); // 10 console.log(b); // 20 console.log(rest); // [30, 40, 50] ({ a, b } = { a: 10, b: 20 }); console.log(a); // 10 console.log(b); // 20 // stage 4(finished) proposal ({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}); console.log(a); // 10 console.log(b); // 20 console.log(rest); // {c: 30, d: 40} description the object and array literal expressions provide an easy way to create ad hoc packages of data.
... examples array destructuring basic variable assignment const foo = ['one', 'two', 'three']; const [red, yellow, green] = foo; console.log(red); // "one" console.log(yellow); // "two" console.log(green); // "three" assignment separate from declaration a variable can be assigned its value via destructuring separate from the variable's declaration.
...And 9 more matches
Using the WebAssembly JavaScript API - WebAssembly
these methods are easier than their non-streaming counterparts, because they can turn the byte code directly into module/instance instances, cutting out the need to separately put the response into an arraybuffer.
... these methods don't directly access the byte code, so require an extra step to turn the response into an arraybuffer before compiling/instantiating the wasm module.
... the equivalent code would look like this: fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.instantiate(bytes, importobject) ).then(results => { results.instance.exports.exported_func(); }); viewing wasm in developer tools in firefox 54+, the developer tool debugger panel has functionality to expose the text representation of any wasm code included in a web page.
...And 9 more matches
JXON - Archive of obsolete content
onode.nodevalue.trim() : onode.nodevalue; } // nodetype is "text" (3) or "cdatasection" (4) else if (onode.nodetype === 1 && !onode.prefix) { // nodetype is "element" (1) sprop = onode.nodename.tolowercase(); vcontent = new jxontree(onode); if (this.hasownproperty(sprop)) { if (this[sprop].constructor !== array) { this[sprop] = [this[sprop]]; } this[sprop].push(vcontent); } else { this[sprop] = vcontent; nlength++; } } } this.keyvalue = parsetext(scollectedtxt); } else { this.keyvalue = null; } if (oparentnode.hasattributes && oxmlparent.hasattributes()) { var oattrib; this.keyattributes = {}; for (nattrlen; nattrlen < oxmlparent.attributes.length; nattrle...
...onode.nodevalue.trim() : onode.nodevalue; } else if (onode.nodetype === 1 && !onode.prefix) { sprop = onode.nodename.tolowercase(); vcontent = new jxontree(onode); if (this.hasownproperty(sprop)) { if (this[sprop].constructor !== array) { this[sprop] = [this[sprop]]; } this[sprop].push(vcontent); } else { this[sprop] = vcontent; } } } if (scollectedtxt) { this.keyvalue = parsetext(scollectedtxt); } } if (oparentnode.hasattributes && oxmlparent.hasattributes()) { var oattrib; for (var nattrib = 0; nattrib < oxmlparent.attributes.length; nattrib++) { oattrib = oxmlparent.attribute...
...e.nodetype === 3) { scollectedtxt += onode.nodevalue.trim(); } /* nodetype is "text" (3) */ else if (onode.nodetype === 1 && !onode.prefix) { /* nodetype is "element" (1) */ if (nlength === 0) { vresult = {}; } sprop = onode.nodename.tolowercase(); vcontent = getjxontree(onode); if (vresult.hasownproperty(sprop)) { if (vresult[sprop].constructor !== array) { vresult[sprop] = [vresult[sprop]]; } vresult[sprop].push(vcontent); } else { vresult[sprop] = vcontent; nlength++; } } } } if (scollectedtxt) { nlength > 0 ?
...And 8 more matches
LiveConnect Overview - Archive of obsolete content
javascript to java communication when you refer to a java package or class, or work with a java object or array, you use one of the special liveconnect objects.
... table 9.1 the liveconnect objects object description javaarray a wrapped java array, accessed from within javascript code.
...for example, you can use the following: var mystring = new java.lang.string("hello world"); instead of the longer version: var mystring = new packages.java.lang.string("hello world"); working with java arrays when any java method creates an array and you reference that array in javascript, you are working with a javaarray.
...And 8 more matches
Looping code - Learn web development
this shows a loop is used to iterate over the items in an array and do something with each of them — a very common pattern in javascript.
... the loop has been told to run until i is no longer smaller than the length of the cats array.
... note: we have made the condition i < cats.length, not i <= cats.length, because computers count from 0, not 1 — we are starting i at 0, and going up to i = 4 (the index of the last array item).
...And 8 more matches
Dict.jsm
method overview dict copy(); boolean del(string akey); object get(string akey, [optional] object adefault); boolean has(string akey); array listitems(); array listkeys(); array listvalues(); void set(string akey, object avalue); string tojson(); string tostring(); properties attribute type description count number the number of items in the dictionary.
... items iterator returns an iterator over all of the items in the dictionary; each item is returned as a pair (a two-element array) with the first element being the key and the second being the value.
... listitems() returns an array of the key/value pairs in the dictionary.
...And 8 more matches
nss tech note1
the number of required templates is determined by the type of the first template.when multiple templates are required, the pointer must point to a null-terminated array of templates.
...a "null template" is a template that is all zeros, having a zero kind.† the term "null-terminated array", as used throughout this document, means an array of templates, the last of which is a null template.
...if kind is an asn.1 sequence tag (sec_asn1_sequence), then you must specify additional templates in a null-terminated array to define the content of the of the asn.1 sequence.
...And 8 more matches
nss tech note5
<big>(for example)</big> choose a slot on which to to do the operation pk11slotinfo* slot = pk11_getbestslot(ciphermech, null); or pk11slotinfo* slot = pk11_getinternalkeyslot(); /* alwys returns internal slot, may not be optimal */ prepare the key if using a raw key /* turn the raw key into a secitem */ secitem keyitem; keyitem.data = /* ptr to an array of key bytes */ keyitem.len = /* length of the array of key bytes */ /* turn the secitem into a key object */ pk11symkey* symkey = pk11_importsymkey(slot, ciphermech, pk11_originunwrap, cka_encrypt, &keyitem, null); if generating the key - see section generate a s...
...if not using cbc mode, just pass a null iv parm to pk11_paramfromiv function secitem ivitem; ivitem.data = /* ptr to an array of iv bytes */ ivitem.len = /* length of the array of iv bytes */ secitem *secparam = pk11_paramfromiv(ciphermech, &ivitem);</big> <big>now encrypt and decrypt using the key and parameter setup in above steps</big> create encryption context pk11context* enccontext = pk11_createcontextbysymkey(ciphermech, cka_encrypt or cka_decrypt, ...
...md5 <big>(for example)</big> choose a slot on which to to do the operation pk11slotinfo* slot = pk11_getbestslot(digestmech, null); or pk11slotinfo* slot = pk11_getinternalkeyslot(); /* always returns int slot, may not be optimal */ prepare the key if using a raw key /* turn the raw key into a secitem */ secitem keyitem; keyitem.data = /* ptr to an array of key bytes */ keyitem.len = /* length of the array of key bytes */ /* turn the secitem into a key object */ pk11symkey* symkey = pk11_importsymkey(slot, digestmech, pk11_originunwrap, cka_digest, &keyitem, null); if generating the key - see section generate a sy...
...And 8 more matches
JSAPI User Guide
spidermonkey provides a few core javascript data types—numbers, strings, arrays, objects, and so on—and a few methods, such as array.push.
...the application starts out by creating an object and populating it with the standard javascript classes, like array and object.
... jsautocompartment ac(cx, global); // populate the global object with the standard globals, like object and // array.
...And 8 more matches
nsIBrowserSearchService
void addengine(in astring engineurl, in long datatype, in astring iconurl, in boolean confirm, [optional] in nsisearchinstallcallback callback); void addenginewithdetails(in astring name, in astring iconurl, in astring alias, in astring description, in astring method, in astring url); void getdefaultengines([optional] out unsigned long enginecount, [retval, array, size_is(enginecount)] out nsisearchengine engines); nsisearchengine getenginebyalias(in astring alias); nsisearchengine getenginebyname(in astring aenginename); void getengines([optional] out unsigned long enginecount, [retval, array, size_is(enginecount)] out nsisearchengine engines); void getvisibleengines([optional] out unsigned ...
...long enginecount, [retval, array, size_is(enginecount)] out nsisearchengine engines); void init([optional] in nsibrowsersearchinitobserver observer); void moveengine(in nsisearchengine engine, in long newindex); void removeengine(in nsisearchengine engine); void restoredefaultengines(); attributes attribute type description currentengine nsisearchengine the currently active search engine.
... getdefaultengines() returns an array of all default search engines.
...And 8 more matches
nsIDOMWindowUtils
adelta, in long amodifiers); void sendtextevent(in astring acompositionstring, in long afirstclauselength, in unsigned long afirstclauseattr, in long asecondclauselength, in unsigned long asecondclauseattr, in long athirdclauselength, in unsigned long athirdclauseattr, in long acaretstart, in long acaretlength); obsolete since gecko 26 boolean sendtouchevent(in astring atype, [array, size_is(count)] in pruint32 aidentifiers, [array, size_is(count)] in print32 axs, [array, size_is(count)] in print32 ays, [array, size_is(count)] in pruint32 arxs, [array, size_is(count)] in pruint32 arys, [array, size_is(count)] in float arotationangles, [array, size_is(count)] in float aforces, in pruint32 count, in long amodifiers, [optional] in boolean aignorerootscrollframe); void...
... query_text_rect_array 3209 selection_set_flag_use_native_line_break 0x0000 one of values of aadditionalflags of sendselectionsetevent().
... boolean sendtouchevent( in astring atype, [array, size_is(count)] in pruint32 aidentifiers, [array, size_is(count)] in print32 axs, [array, size_is(count)] in print32 ays, [array, size_is(count)] in pruint32 arxs, [array, size_is(count)] in pruint32 arys, [array, size_is(count)] in float arotationangles, [array, size_is(count)] in float aforces, in pruint32 count, in long amodifiers, [optional] in boolean aignorerootscrollfram...
...And 8 more matches
nsINavBookmarksService
aindex); note: renamed from createcontainer in gecko 1.9 obsolete since gecko 13.0 long long createfolder(in long long aparentfolder, in autf8string name, in long index); void endupdatebatch(); obsolete since gecko 1.9 void exportbookmarkshtml(in nsifile file); obsolete since gecko 1.9 nsiuri getbookmarkedurifor(in nsiuri auri); void getbookmarkfolderstarray(in nsiuri auri, in print64array aresult); native code only!
... obsolete since gecko 1.9 void getbookmarkidsforuri(in nsiuri auri, [optional] out unsigned long count, [array, retval, size_is(count)] out long long bookmarks); note: renamed from getbookmarkfolders in gecko 1.9 void getbookmarkidsforuritarray(in nsiuri auri, in print64array aresult); native code only!
... return value native code only!getbookmarkfolderstarray obsolete since gecko 1.9 (firefox 3)this feature is obsolete.
...And 8 more matches
BiquadFilterNode.getFrequencyResponse() - Web APIs
the getfrequencyresponse() method of the biquadfilternode interface takes the current filtering algorithm's settings and calculates the frequency response for frequencies specified in a specified array of frequencies.
... the two output arrays, magresponseoutput and phaseresponseoutput, must be created before calling this method; they must be the same size as the array of input frequency values (frequencyarray).
... syntax biquadfilternode.getfrequencyresponse(frequencyarray, magresponseoutput, phaseresponseoutput); parameters frequencyarray a float32array containing an array of frequencies, specified in hertz, which you want to filter.
...And 8 more matches
WebGLRenderingContext.getVertexAttrib() - Web APIs
possible values: gl.vertex_attrib_array_buffer_binding: returns the currently bound webglbuffer.
... gl.vertex_attrib_array_enabled: returns a glboolean that is true if the vertex attribute is enabled at this index.
... gl.vertex_attrib_array_size: returns a glint indicating the size of an element of the vertex array.
...And 8 more matches
WebGL best practices - Web APIs
take advantage of universally supported webgl 1 extensions these webgl 1 extensions are universally supported: angle_instanced_arrays ext_blend_minmax oes_element_index_uint oes_standard_derivatives oes_vertex_array_object webgl_debug_renderer_info webgl_lose_context (see also: https://jdashg.github.io/misc/webgl/webgl-feature-levels.html) consider polyfilling these into webglrenderingcontext, like: https://github.com/jdashg/misc/blob/master/webgl/webgl-v1.1.js universally supported limits the minimum requirements f...
... and to a lesser degree, vao attachments (vertexattribpointer, disable/enablevertexattribarray) drawing from static, unchanging vaos is faster than mutating the same vao for every draw call.
... always keep vertex attrib 0 array-enabled if you draw with vertex attrib 0 array disabled, you will force the browser to do complicated emulation when running on desktop opengl (such as on macos).
...And 8 more matches
Rest parameters - JavaScript
the rest parameter syntax allows us to represent an indefinite number of arguments as an array.
...which will cause all remaining (user supplied) arguments to be placed within a "standard" javascript array.
...formally defined in function expression), while the arguments object contains all arguments passed to the function; the arguments object is not a real array, while rest parameters are array instances, meaning methods like sort, map, foreach or pop can be applied on it directly; the arguments object has additional functionality specific to itself (like the callee property).
...And 8 more matches
JSON.stringify() - JavaScript
the json.stringify() method converts a javascript object or value to a json string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
... replacer optional a function that alters the behavior of the stringification process, or an array of string and number that serve as an allowlist for selecting/filtering the properties of the value object to be included in the json string.
...if any such values are encountered during conversion they are either omitted (when found in an object) or changed to null (when found in an array).
...And 8 more matches
Understanding WebAssembly text format - WebAssembly
next, we’ll load our binary into a typed array called addcode (as described in fetching webassembly bytecode), compile and instantiate it, and execute our add function in javascript (we can now find add() in the exports property of the instance): webassembly.instantiatestreaming(fetch('add.wasm')) .then(obj => { console.log(obj.instance.exports.add(1, 2)); // "3" }); note: you can find this example in github as add.html (see it li...
...according to webassembly, memory is just a large array of bytes that can grow over time.
... from javascript’s point of view, it’s as though memory is all inside one big (resizable) arraybuffer.
...And 8 more matches
widget - Archive of obsolete content
we could implement the main user interface as a widget hosting an array of buttons to control play/pause/stop functions.
... contentscriptfile string,array a local file url or an array of local file urls of content scripts to load.
... contentscript string,array a string or an array of strings containing the texts of content scripts to load.
...And 7 more matches
TypeScript support in Svelte - Learn web development
(ts) $: completedtodos = todos.filter(t => t.completed).length we will use the todotype we already defined to tell typescript that todos is a todotype array — replace your export let todos line with the following: import type { todotype } from '../types/todo.type' export let todos: todotype[] notice that now typescript can infer that the t variable in todos.filter(t => t.completed) is of type todotype.
... start by importing the todotype and telling typescript that our todos variable is an array of todotype.
...(ts) <todo {todo} this is because the todos prop in the todosstatus component has no default value, so typescript has inferred it to be of type undefined, which is not compatible with an array of todotype.
...And 7 more matches
JIT Optimization Outcomes
arraybadflags the array being accessed may have flags that the optimization strategy cannot handle.
... for example, if the array has sparse indexes, or has indexes that overflow the array's length, the optimization strategy may fail.
... arraydoubleconversion the type-system indicates that some arrays at this site should be converted to packed arrays of doubles while others should not.
...And 7 more matches
imgIContainer
as a service: var imgicontainer = components.classes["@mozilla.org/????????????????????????????"] .createinstance(components.interfaces.imgicontainer); method overview void addrestoredata([array, size_is(acount), const] in char data, in unsigned long acount); native code only!
... obsolete since gecko 2.0 void appendframe(in print32 ax, in print32 ay, in print32 awidth, in print32 aheight, in gfximageformat aformat, [array, size_is(imagelength)] out pruint8 imagedata, out unsigned long imagelength); native code only!
... obsolete since gecko 2.0 void appendpalettedframe(in print32 ax, in print32 ay, in print32 awidth, in print32 aheight, in gfximageformat aformat, in pruint8 apalettedepth, [array, size_is(imagelength)] out pruint8 imagedata, out unsigned long imagelength, [array, size_is(palettelength)] out pruint32 palettedata, out unsigned long palettelength); native code only!
...And 7 more matches
nsIConsoleService
inherits from: nsisupports last changed in gecko 19 (firefox 19 / thunderbird 19 / seamonkey 2.16) implemented by: @mozilla.org/consoleservice;1 as a service: var consoleservice = components.classes["@mozilla.org/consoleservice;1"] .getservice(components.interfaces.nsiconsoleservice); method overview void getmessagearray([array, size_is(count)] out nsiconsolemessage messages, out uint32_t count);obsolete since gecko 19 void getmessagearray([optional] out uint32_t count, [retval, array, size_is(count)] out nsiconsolemessage messages); void logmessage(in nsiconsolemessage message); void logstringmessage(in wstring message); void registerlistener(in nsiconsolelistener listener); ...
... void reset(); void unregisterlistener(in nsiconsolelistener listener); methods getmessagearray() to obtain an array of all logged messages.
... void getmessagearray( [array, size_is(count)] out nsiconsolemessage messages, out pruint32 count ); parameters messages an array of logged messages.
...And 7 more matches
nsITreeView
ex, in boolean before); obsolete since gecko 1.8 boolean candropon(in long index); obsolete since gecko 1.8 void cyclecell(in long row, in nsitreecolumn col); void cycleheader(in nsitreecolumn col); void drop(in long row, in long orientation, in nsidomdatatransfer datatransfer); astring getcellproperties(in long row, in nsitreecolumn col, in nsisupportsarray properties obsolete since gecko 22); astring getcelltext(in long row, in nsitreecolumn col); astring getcellvalue(in long row, in nsitreecolumn col); astring getcolumnproperties(in nsitreecolumn col, in nsisupportsarray properties obsolete since gecko 22); astring getimagesrc(in long row, in nsitreecolumn col); long getlevel(in long index); lo...
...ng getparentindex(in long rowindex); long getprogressmode(in long row, in nsitreecolumn col); astring getrowproperties(in long index, in nsisupportsarray properties obsolete since gecko 22); boolean hasnextsibling(in long rowindex, in long afterindex); boolean iscontainer(in long index); boolean iscontainerempty(in long index); boolean iscontaineropen(in long index); boolean iseditable(in long row, in nsitreecolumn col); boolean isselectable(in long row, in nsitreecolumn col); boolean isseparator(in long index); boolean issorted(); void performaction(in wstring action); void performactiononcell(in wstring action, in long row, in nsitreecolumn col); void performactiononrow(in wst...
... astring getcellproperties( in long row, in nsitreecolumn col, in nsisupportsarray properties ); parameters row the index of the row.
...And 7 more matches
XPIDL
array<t> const nstarray<t>& nstarray<t>& array the c++-exposed type t will be an owned variant.
...webidl types will be passed as mozilla::dom::interfacename* when used as in-parameters, as mozilla::dom::interfacename** when used as out or inout-parameters, and as refptr<mozilla::dom::interfacename> when used as an array element.
...the array property turns the parameter into an array; the parameter must also have a corresponding size_is property whose argument is the parameter that has the size of the array.
...And 7 more matches
Declaring types
primitive types primitive types are those types that represent a single value in memory, as opposed to arrays, structures, or functions.
...this method accepts as input the name of the structure and an array of field descriptors, each describing one field in the structure.
... you can, optionally, leave out the field descriptor array; this creates an opaque structure whose contents are not defined.
...And 7 more matches
Type conversion
implicit convert in js-ctypes, data could be converted implicitly when passing to or returning from a functiontype call, or setting pointer content, an array element or a struct field.
... var buffer = ctypes.char.array(10)(); var somecfunction = library.declare("somecfunction", ctypes.default_abi, ctypes.void_t, ctypes.char.ptr); somecfunction(buffer); // here ctypes.char.array(10)() is converted to ctypes.char.ptr type implicit conversion can be tested in the following way: var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.bool } ])(); mystruct.v = 1; console.log(mystruct.v.tostring()); // 'true' boolean type target type source converted value ctypes.bool js boolean src js number (0 or 1) if src == 0: false if src == 1: true var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.bool } ])(); mystruct.v = true; console.log(mystruct.v.tostring()); // 'true' mystruct.v = false; console...
...v.tostring()); // 10 mystruct.v = ctypes.int32_t(10); // throws error float types target type source converted value any float types js number (only if fits to the size) src pointer types target type source converted value any pointer types null nullptr ctypes.voidptr_t any pointer types src any array types src.addressofelement(0) ctypes.pointertype(t) ctypes.arraytype(t) src.addressofelement(0) ctypes.arraytype(t, n) src.addressofelement(0) var mystruct = ctypes.structtype("mystructtype", [ { "v": ctypes.int16_t.ptr } ])(); mystruct.v = ctypes.int16_t.array(10)(); console.log(mystruct.v.tostring()); // 'ctypes.int16_t.ptr(ctypes.uint64("0x11d6ff400...
...And 7 more matches
Debugger.Object - Firefox Developer Tools
for example: function h() { var i = function() {}; // display name: h/i f(function () {}); // display name: h/< } var s = f(function () {}); // display name: s< parameternames if the referent is a debuggee function, the names of the its parameters, as an array of strings.
... if the referent is a host function for which parameter names are not available, return an array with one element per parameter, each of which is undefined.
... if the referent is a function proxy, return an empty array.
...And 7 more matches
Pixel manipulation with canvas - Web APIs
with the imagedata object you can directly read and write a data array to manipulate pixel data.
... data a uint8clampedarray representing a one-dimensional array containing the data in the rgba order, with integer values between 0 and 255 (included).
... the data property returns a uint8clampedarray which can be accessed to look at the raw pixel data; each pixel is represented by four one-byte values (red, green, blue, and alpha, in that order; that is, "rgba" format).
...And 7 more matches
WebGLRenderingContext.getParameter() - Web APIs
constant returned type description gl.active_texture glenum gl.aliased_line_width_range float32array (with 2 elements) gl.aliased_point_size_range float32array (with 2 elements) gl.alpha_bits glint gl.array_buffer_binding webglbuffer gl.blend glboolean gl.blend_color float32array (with 4 values) gl.blend_dst_alpha glenum gl.blend_dst_rgb glenum gl.blend_equation glenum ...
... gl.blend_equation_alpha glenum gl.blend_equation_rgb glenum gl.blend_src_alpha glenum gl.blend_src_rgb glenum gl.blue_bits glint gl.color_clear_value float32array (with 4 values) gl.color_writemask sequence<glboolean> (with 4 values) gl.compressed_texture_formats uint32array returns the compressed texture formats.
... gl.depth_bits glint gl.depth_clear_value glfloat gl.depth_func glenum gl.depth_range float32array (with 2 elements) gl.depth_test glboolean gl.depth_writemask glboolean gl.dither glboolean gl.element_array_buffer_binding webglbuffer gl.framebuffer_binding webglframebuffer or null null corresponds to a binding to the default framebuffer.
...And 7 more matches
A basic 2D WebGL animation example - Web APIs
let gl = null; let glcanvas = null; // aspect ratio and coordinate system // details let aspectratio; let currentrotation = [0, 1]; let currentscale = [1.0, 1.0]; // vertex information let vertexarray; let vertexbuffer; let vertexnumcomponents; let vertexcount; // rendering data shared with the // scalers.
...entbyid("glcanvas"); gl = glcanvas.getcontext("webgl"); const shaderset = [ { type: gl.vertex_shader, id: "vertex-shader" }, { type: gl.fragment_shader, id: "fragment-shader" } ]; shaderprogram = buildshaderprogram(shaderset); aspectratio = glcanvas.width/glcanvas.height; currentrotation = [0, 1]; currentscale = [1.0, aspectratio]; vertexarray = new float32array([ -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5 ]); vertexbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, vertexbuffer); gl.bufferdata(gl.array_buffer, vertexarray, gl.static_draw); vertexnumcomponents = 2; vertexcount = vertexarray.length/vertexnumcomponents; currentangle = 0.0; rotationrate = 6; animatescene(); }...
...the array shaderset contains a list of objects, each describing one shader function to be compiled into the program.
...And 7 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
xit) { return false; } } amap.length--; return true; } function typewrite () { if (spart.length === 0 && scroll(asheets[nidx], 0, true) && nidx++ === asheets.length - 1) { clean(); return; } ocurrent.nodevalue += spart.charat(0); spart = spart.slice(1); } function sheet (onode) { this.ref = onode; if (!onode.haschildnodes()) { return; } this.parts = array.prototype.slice.call(onode.childnodes); for (var nchild = 0; nchild < this.parts.length; nchild++) { onode.removechild(this.parts[nchild]); this.parts[nchild] = new sheet(this.parts[nchild]); } } var nintervid, ocurrent = null, btyping = false, bstart = true, nidx = 0, spart = "", asheets = [], amap = []; this.rate = nrate || 100; this.play = function () { ...
...*/) { var aargs = array.prototype.slice.call(arguments, 2); return __nativest__(vcallback instanceof function ?
...*/) { var aargs = array.prototype.slice.call(arguments, 2); return __nativesi__(vcallback instanceof function ?
...And 7 more matches
JavaScript data types and data structures - JavaScript
special non-data but structural type for any constructed object instance also used as data structures: new object, new array, new map, new set, new weakmap, new set, new date and almost everything made with new keyword; function : a non-data structure, though it also answers for typeof operator: typeof instance === "function".
...javascript offers other means to represent a set of booleans (like an array of booleans, or an object with boolean values assigned to named properties).
...for instance, with a separator, one could emulate a list (while a javascript array would be more suitable).
...And 7 more matches
Regular expressions - JavaScript
it returns an array of information or null on a mismatch.
... match() returns an array containing all of the matches, including capturing groups, or null if no match is found.
... split() uses a regular expression or a fixed string to break a string into an array of substrings.
...And 7 more matches
Loading and running WebAssembly code - WebAssembly
the older webassembly.compile/webassembly.instantiate methods require you to create an arraybuffer containing your webassembly module binary after fetching the raw bytes, and then compile/instantiate it.
... this is analogous to new function(string), except that we are substituting a string of characters (javascript source code) with an array buffer of bytes (webassembly source code).
... the newer webassembly.compilestreaming/webassembly.instantiatestreaming methods are a lot more efficient — they perform their actions directly on the raw stream of bytes coming from the network, cutting out the need for the arraybuffer step.
...And 7 more matches
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
parameters menuitems an array of menuitems.
...the items property may be used to define an array of menuitems.
... items array an array of menuitems in the menu.
...And 6 more matches
tabbrowser - Archive of obsolete content
tabs type: array a nodelist containing the tab objects for each tab in the tabbrowser.
... visibletabs type: array an array containing tab objects for each visible tab in the tabbrowser.
...the argument should be an array of objects, one for each document to load.
...And 6 more matches
Index - Learn web development
64 introducing javascript objects article, assessment, beginner, codingscripting, guide, javascript, learn, objects, tutorial in javascript, most things are objects, from core javascript features like arrays to the browser apis built on top of javascript.
... 74 working with json article, beginner, codingscripting, guide, json, json api, json arrays, json parsing, json structure, javascript, learn, objects, tutorial, l10n:priority in this article, we've given you a simple guide to using json in your programs, including how to create and parse json, and how to access data locked inside it.
... 75 javascript first steps arrays, article, assessment, beginner, codingscripting, guide, javascript, landing, module, numbers, operators, variables, l10n:priority, maths, strings in our first javascript module, we first answer some fundamental questions such as "what is javascript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing javascript.
...And 6 more matches
Solve common problems in your JavaScript code - Learn web development
what is an array?
... arrays how do you create an array?
... how do you access and modify the items in an array?
...And 6 more matches
PromiseWorker.jsm
aargs an array of arguments to pass to the function named afunctionname in the worker file.
... if the worker function does not have any arguments and the empty array should be passed here.
... atransferlist optional an optional array of transferable objects to transfer ownership of.
...And 6 more matches
JS_DefineConstDoubles
cds jsconstdoublespec * pointer to an array of jsconstdoublespec records containing property names and values to create.
... the last array element must contain zero-valued members.
... cis jsconstintegerspec * pointer to an array of jsconstintegerspec records containing property names and values to create.
...And 6 more matches
Secure Development Guidelines
a/b : 0; } writing secure code: memory management string handling c-style strings are byte arrays that end with a \0 byte some string handling functions won’t perform any kind of length checking, so don’t use them ensure your string is always \0 terminated!
... buffer bounds validations (bbv) thou shalt check the array bounds of all strings (indeed, all arrays), for surely where thou typest "foo" someone someday shall type "supercalifragilisticexpialidocious".
... most memory allocators use a linked list or binary tree bbv: off-by-one the array index starts at 0 not at 1 char array[1024]; array[0] = first element!
...And 6 more matches
IAccessibleTable
refer to @ref _arrayconsideration "special consideration when using arrays" for more details.
... children an array of cell indexes of selected cells (each index is 0 based), allocated by the server.
...nchildren the number of cell indexes returned; the size of the returned array.
...And 6 more matches
inIDOMUtils
ar inidomutils = components.classes["@mozilla.org/inspector/dom-utils;1"] .getservice(components.interfaces.inidomutils); method overview void addpseudoclasslock(in nsidomelement aelement, in domstring apseudoclass); void clearpseudoclasslocks(in nsidomelement aelement); [implicit_jscontext] jsval colornametorgb(in domstring acolorname); nsiarray getbindingurls(in nsidomelement aelement); nsidomnodelist getchildrenfornode(in nsidomnode anode, in boolean ashowinganonymouscontent); unsigned long long getcontentstate(in nsidomelement aelement); void getcsspropertynames([optional] in unsigned long aflags, [optional] out unsigned long acount, [retval, array, size_is(acount)] out wstring aprops); nsisupport...
...sarray getcssstylerules(in nsidomelement aelement, [optional] in domstring apseudo); nsidomnode getparentfornode(in nsidomnode anode, in boolean ashowinganonymouscontent); unsigned long getruleline(in nsidomcssstylerule arule); unsigned long getrulecolumn(in nsidomcssstylerule arule); unsigned long getselectorcount(in nsidomcssstylerule arule); astring getselectortext(in nsidomcssstylerule arule, in unsigned long aselectorindex); unsigned long long getspecificity(in nsidomcssstylerule arule, in unsigned long aselectorindex); nsidomfontfacelist getusedfontfaces(in nsidomrange arange); bool haspseudoclasslock(in nsidomelement aelement, in domstring apseudoclass); boolean isignorablewhitespace(in nsidomcharacterdata ...
... value state 1 :active 2 :focus 4 :hover 8 :-moz-drag-over 16 :target 1<<29 :-moz-focusring methods getbindingurls() returns an array of nsiuri objects representing the current xml binding for the specified element.
...And 6 more matches
nsIBinaryInputStream
inherits from: nsiinputstream last changed in gecko 1.7 method overview pruint8 read8(); pruint16 read16(); pruint32 read32(); pruint64 read64(); unsigned long readarraybuffer(in pruint32 alength, in jsval aarraybuffer); prbool readboolean(); void readbytearray(in pruint32 alength, [array, size_is(alength), retval] out pruint8 abytes); void readbytes(in pruint32 alength, [size_is(alength), retval] out string astring); acstring readcstring(); double readdouble(); float readfloat(); astring readstring()...
... readarraybuffer() read opaque bytes from the stream, storing the results in an arraybuffer.
... unsigned long readarraybuffer(in pruint32 alength, in jsval aarraybuffer); parameters alength the number of bytes that should be read.
...And 6 more matches
CType
arraytype these represent c arrays.
... method overview methods available on all ctype objects ctype array([n]) string tosource() string tostring() properties properties of all ctype objects these properties are available on all ctype objects.
...for other function, pointer, and array types, this should be a valid c type expression.
...And 6 more matches
AnalyserNode.getFloatFrequencyData() - Web APIs
the getfloatfrequencydata() method of the analysernode interface copies the current frequency data into a float32array array passed into it.
... each item in the array represents the decibel value for a specific frequency.
...for example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 hz.
...And 6 more matches
Console.table() - Web APIs
WebAPIConsoletable
this function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.
...each element in the array (or enumerable property if data is an object) will be a row in the table.
...if data is an array, then its values will be the array indices.
...And 6 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
consider code such as this: customelement.prototype.getdata = url => { if (this.cache[url]) { this.data = this.cache[url]; this.dispatchevent(new event("load")); } else { fetch(url).then(result => result.arraybuffer()).then(data => { this.cache[url] = data; this.data = data; this.dispatchevent(new event("load")); }); } }; the problem introduced here is that by using a task in one branch of the if...else statement (in the case in which the image is available in the cache) but having promises involved in the else clause, we have a situation in which the order of operations can va...
... we can ensure consistent ordering of these operations by using a microtask in the if clause to balance the two clauses: customelement.prototype.getdata = url => { if (this.cache[url]) { queuemicrotask(() => { this.data = this.cache[url]; this.dispatchevent(new event("load")); }); } else { fetch(url).then(result => result.arraybuffer()).then(data => { this.cache[url] = data; this.data = data; this.dispatchevent(new event("load")); }); } }; this balances the clauses by having both situations handle the setting of data and firing of the load event within a microtask (using queuemicrotask() in the if clause and using the promises used by fetch() in the else clause).
... the snippet below creates a function that batches multiple messages into an array, using a microtask to send them as a single object when the context exits.
...And 6 more matches
IIRFilterNode.getFrequencyResponse() - Web APIs
the getfrequencyresponse() method of the iirfilternode interface takes the current filtering algorithm's settings and calculates the frequency response for frequencies specified in a specified array of frequencies.
... the two output arrays, magresponseoutput and phaseresponseoutput, must be created before calling this method; they must be the same size as the array of input frequency values (frequencyarray).
... syntax iirfilternode.getfrequencyresponse(frequencyarray, magresponseoutput, phaseresponseoutput); parameters frequencyarray a float32array containing an array of frequencies, specified in hertz, which you want to filter.
...And 6 more matches
Intersection Observer API - Web APIs
threshold either a single number or an array of numbers which indicate at what percentage of the target's visibility the observer's callback should be executed.
...if you want the callback to run every time visibility passes another 25%, you would specify the array [0, 0.25, 0.5, 0.75, 1].
... for example, if you want to be informed every time a target's visibility passes backward or forward through each 25% mark, you would specify the array [0, 0.25, 0.5, 0.75, 1] as the list of thresholds when creating the observer.
...And 6 more matches
TextEncoder - Web APIs
example const encoder = new textencoder() const view = encoder.encode('€') console.log(view); // uint8array(3) [226, 130, 172] constructor textencoder() returns a newly constructed textencoder that will generate a byte stream with utf-8 encoding.
... textencoder.prototype.encode() takes a usvstring as input, and returns a uint8array containing utf-8 encoded text.
... textencoder.prototype.encodeinto() takes a usvstring to encode and a destination uint8array to put resulting utf-8 encoded text into, and returns a dictionary object indicating the progress of the encoding.
...And 6 more matches
WebGLRenderingContext.readPixels() - Web APIs
the webglrenderingcontext.readpixels() method of the webgl api reads a block of pixels from a specified rectangle of the current color framebuffer into an arraybufferview object.
... syntax // webgl1: void gl.readpixels(x, y, width, height, format, type, pixels); // webgl2: void gl.readpixels(x, y, width, height, format, type, glintptr offset); void gl.readpixels(x, y, width, height, format, type, arraybufferview pixels, gluint dstoffset); parameters x a glint specifying the first horizontal pixel that is read from the lower left corner of a rectangular block of pixels.
...possible values: gl.unsigned_byte gl.unsigned_short_5_6_5 gl.unsigned_short_4_4_4_4 gl.unsigned_short_5_5_5_1 gl.float webgl2 adds gl.byte gl.unsigned_int_2_10_10_10_rev gl.half_float gl.short gl.unsigned_short gl.int gl.unsigned_int gl.unsigned_int_10f_11f_11f_rev gl.unsigned_int_5_9_9_9_rev pixels an arraybufferview object to read data into.
...And 6 more matches
Matrix math for the web - Web APIs
in javascript, it is easy to represent a matrix as an array.
...lt0[2], result0[3], result1[0], result1[1], result1[2], result1[3], result2[0], result2[1], result2[2], result2[3], result3[0], result3[1], result3[2], result3[3] ]; } let's look at this function in action: let somematrix = [ 4, 0, 0, 0, 0, 3, 0, 0, 0, 0, 5, 0, 4, 8, 4, 1 ] let identitymatrix = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; // returns a new array equivalent to somematrix let somematrixresult = multiplymatrices(identitymatrix, somematrix); important: these matrix functions are written for clarity of explanation, not for speed or memory management.
... these functions create a lot of new arrays, which can be particularly expensive for real-time operations due to garbage collection.
...And 6 more matches
Creating 3D objects using WebGL - Web APIs
to do this efficiently, we're going to switch from drawing using the vertices directly by calling the gl.drawarrays() method to using the vertex array as a table, and referencing individual vertices in that table to define the positions of each face's vertices, by calling gl.drawelements().
...we can pass a lot fewer data around by building an array of all 24 vertices, then referring to each vertex by its index into that array instead of moving entire sets of coordinates around.
... gl.vertexattribpointer( programinfo.attriblocations.vertexposition, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexposition); } define the vertices' colors we also need to build an array of colors for each of the 24 vertices.
...And 6 more matches
Using Web Workers - Web APIs
nsole.log('message posted to worker'); } second.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } so here we have two <input> elements represented by the variables first and second; when the value of either is changed, myworker.postmessage([first.value,second.value]) is used to send the value inside both to the worker, as an array.
... */ this.sendquery = function() { if (arguments.length < 1) { throw new typeerror('queryableworker.sendquery takes at least one argument'); return; } worker.postmessage({ 'querymethod': arguments[0], 'queryarguments': array.prototype.slice.call(arguments, 1) }); } we finish queryableworker with the onmessage method.
...eply('printstuff', a - b); }, waitsometime: function() { settimeout(function() { reply('doalert', 3, 'seconds'); }, 3000); } } function reply() { if (arguments.length < 1) { throw new typeerror('reply - takes at least one argument'); return; } postmessage({ querymethodlistener: arguments[0], querymethodarguments: array.prototype.slice.call(arguments, 1) }); } /* this method is called when main page calls queryworker's postmessage method directly*/ function defaultreply(message) { // do something } and the onmessage method is now trivial: onmessage = function(event) { if (event.data instanceof object && event.data.hasownproperty('querymethod') && event.data.hasownproperty('queryme...
...And 6 more matches
Sending and Receiving Binary Data - Web APIs
receiving binary data using javascript typed arrays the responsetype property of the xmlhttprequest object can be set to change the expected response type from the server.
... possible values are the empty string (default), "arraybuffer", "blob", "document", "json", and "text".
... the response property will contain the entity body according to responsetype, as an arraybuffer, blob, document, json, or string.
...And 6 more matches
Expressions and operators - JavaScript
destructuring for more complex assignments, the destructuring assignment syntax is a javascript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
... for example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once.
... the code prints the values of the diagonal elements in the array: var x = [0,1,2,3,4,5,6,7,8,9] var a = [x, x, x, x, x]; for (var i = 0, j = 9; i <= j; i++, j--) // ^ console.log('a[' + i + '][' + j + ']= ' + a[i][j]); unary operators a unary operation is an operation with only one operand.
...And 6 more matches
Functions - JavaScript
a non-primitive value, such as array or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function, as shown in the following example: function myfunc(theobject) { theobject.make = 'toyota'; } var mycar = {make: 'honda', model: 'accord', year: 1998}; var x, y; x = mycar.make; // x gets the value "honda" myfunc(mycar); y = mycar.make; // y gets the value "...
...the following example shows a map function that should receive a function as first argument and an array as second argument.
... function map(f, a) { let result = []; // create a new array let i; // declare variable for (i = 0; i != a.length; i++) result[i] = f(a[i]); return result; } in the following code, the function receives a function defined by a function expression and executes it for every element of the array received as a second argument.
...And 6 more matches
Object.entries() - JavaScript
the object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop.
... the order of the array returned by object.entries() does not depend on how an object is defined.
... if there is a need for certain ordering, then the array should be sorted first, like object.entries(obj).sort((a, b) => b[0].localecompare(a[0]));.
...And 6 more matches
Object.getOwnPropertyNames() - JavaScript
the object.getownpropertynames() method returns an array of all properties (including non-enumerable properties except for those which use symbol) found directly in a given object.
... return value an array of strings that corresponds to the properties found directly in the given object.
... description object.getownpropertynames() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object obj.
...And 6 more matches
delete operator - JavaScript
this includes properties of built-in objects like math, array, object and properties that are created as non-configurable with methods like object.defineproperty().
...however, in the case of internet explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays.
... if you want to use an ordered associative array in a cross-browser environment, use a map object if available, or simulate this structure with two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.
...And 6 more matches
for...of - JavaScript
the for...of statement creates a loop iterating over iterable objects, including: built-in string, array, array-like objects (e.g., arguments or nodelist), typedarray, map, set, and user-defined iterables.
... examples iterating over an array const iterable = [10, 20, 30]; for (const value of iterable) { console.log(value); } // 10 // 20 // 30 you can use let instead of const too, if you reassign the variable inside the block.
... const iterable = [10, 20, 30]; for (let value of iterable) { value += 1; console.log(value); } // 11 // 21 // 31 iterating over a string const iterable = 'boo'; for (const value of iterable) { console.log(value); } // "b" // "o" // "o" iterating over a typedarray const iterable = new uint8array([0x00, 0xff]); for (const value of iterable) { console.log(value); } // 0 // 255 iterating over a map const iterable = new map([['a', 1], ['b', 2], ['c', 3]]); for (const entry of iterable) { console.log(entry); } // ['a', 1] // ['b', 2] // ['c', 3] for (const [key, value] of iterable) { console.log(value); } // 1 // 2 // 3 iterating over a set const iterable = new set([1, 1, 2, 2, 3, 3]); for (const value of iterable) { console.log(value); } // 1 // 2 // 3 iterating o...
...And 6 more matches
page-worker - Archive of obsolete content
include string, regexp, array of (string or regexp) this is useful when your page worker loads a page which will redirect to other pages.
... a match pattern string or an array of match pattern strings.
... contentscriptfile string,array a local file url or an array of local file urls of content scripts to load.
...And 5 more matches
panel - Archive of obsolete content
contentscriptfile string,array a url or an array of urls.
... contentscript string,array a string or an array of strings containing the texts of content scripts to load.
... contentstylefile string, array a url or an array of urls.
...And 5 more matches
lang/type - Archive of obsolete content
isarray(value) returns true if value is an array, false otherwise.
... uses native array.isarray.
... let { isarray } = require('sdk/lang/type'); isarray([]); // true isarray({}); // false parameters value : mixed the variable to check.
...And 5 more matches
XPCOM Objects - Archive of obsolete content
this is done for certain value types that are not valid as return values in idl, such as typed arrays.
... void getchildlist(in string astartingat, out unsigned long acount,[array, size_is(acount), retval] out string achildarray); this method returns an array of strings.
...the second one will hold the length of the return array, and the third parameter will hold the array itself.
...And 5 more matches
Implementing controls using the Gamepad API - Game development
nnected (either physically by the user or due to inactivity.) in the demo, the gamepadapi object is used to store everything related to the api: var gamepadapi = { controller: {}, turbo: false, connect: function() {}, disconnect: function() {}, update: function() {}, buttonpressed: function() {}, buttons: [], buttonscache: [], buttonsstatus: [], axesstatus: [] }; the buttons array contains the xbox 360 button layout: buttons: [ 'dpad-up','dpad-down','dpad-left','dpad-right', 'start','back','axis-left','axis-right', 'lb','rb','power','a','b','x','y', ], this can be different for other types of gamepads like the ps3 controller (or a no-name, generic one), so you have to be careful and not just assume the button you're expecting will be the same button you'll actually...
...we are using only one gamepad for this game, so it's a single object instead of an array of gamepads.
... axes: the state of each axis, represented by an array of floating-point values.
...And 5 more matches
Silly story generator - Learn web development
objective: to test comprehension of javascript fundamentals, such as variables, numbers, operators, strings, and arrays.
...in addition you've got a function called randomvaluefromarray() that takes an array, and returns one of the items stored inside the array at random.
... store the first set of three strings inside an array called insertx.
...And 5 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
we'll use array.prototype.map() instead of array.prototype.filter() because we want to return a new array with some changes, instead of deleting something from the array.
... render an array of <filterbutton /> elements that allow users to change the active filter between all, completed, and incomplete.
... at the top of app.js, beneath our imports but above our app() function, let's add an object called filter_map: const filter_map = { all: () => true, active: task => !task.completed, completed: task => task.completed }; the values of filter_map are functions that we will use to filter the tasks data array: the all filter shows all tasks, so we return true for all tasks.
...And 5 more matches
Working with Svelte stores - Learn web development
first of all, add the following line below your todos array: $: console.log('todos', todos) next, update your todos component call as follows: <todos bind:todos /> remember: <todos bind:todos /> is just a shortcut for <todos bind:todos={todos} />.
...you'll see that every modification we make to our todos is reflected in the todos array defined in app.svelte thanks to the bind directive.
...add these lines below the todos array: console.log('todos store - todos:', todos) console.log('todos store content - $todos:', $todos) when you run the app now, you'll see something like this in your web console: as you can see, our store is just an object containing subscribe(), set(), and update() methods, and $todos is our array of todos.
...And 5 more matches
Rendering a list of Vue components - Learn web development
objective: to learn how to loop through an array of data and render it in multiple components.
...this is a built-in vue directive that lets us include a loop inside of our template, repeating the rendering of a template feature for each item in an array.
... we'll use this to iterate through an array of to-do items and display them in our app in separate todoitem components.
...And 5 more matches
IPDL Tutorial
ipdl supports built-in and custom primitive types, as well as unions and arrays.
... struct namevaluepair { nscstring name; nscstring value; }; in implementation code, these structs can be created and used like so: namevaluepair entry(astring, anotherstring); foo(entry.name(), entry.value()); // named accessor functions return references to the members arrays ipdl has simple syntax for arrays: invokemethod(nscstring[] args); in c++ this is translated into a nstarray reference: virtual bool recvinvokemethod(nstarray<nscstring>& args); ipdl's generated data structures can be used in several protocols if they are defined in a separate .ipdlh file.
... class ppluginparent { /* allocate a pplugininstanceparent when the first form of callplugininstanceconstructor is called */ virtual pplugininstanceparent* allocpplugininstance(const nscstring& type, const nstarray<nscstring>& args, int* rv) = 0; /* deallocate the pplugininstanceparent after pplugininstancedestructor is done with it */ virtual bool deallocpplugininstance(pplugininstanceparent* actor) = 0; /* constructor message */ virtual callpplugininstanceconstructor(const nscstring& type, const nstarray<nscstring>& args, int* rv) { /* generated code */ } /* alternate form of constructor mess...
...And 5 more matches
NSS API Guidelines
the preferred format is: "@(#) $rcsfile: nss-guidelines.html, v $ $revision: 48936 $ $date: 2009-08-11 07:45:57 -0700 (tue, 11 aug 2009) $ $name$" you can put the string in a comment or in a static char array.
... use #ifdef debug to include the array in debug builds only.
... the advantage of using an array is that you can use strings(1) to pull the id tags out of a (debug) compiled library.
...And 5 more matches
IAccessibleTable2
[propget] hresult selectedcells( [out, size_is(, nselectedcells,)] iunknown cells, [out] long nselectedcells ); parameters cells pointer to an array of references to selected accessibles.
... the array is allocated by the server.
...nselectedcells the number of accessibles returned; the size of the returned array.
...And 5 more matches
IAccessibleTableCell
columnheadercells() returns the column headers as an array of cell accessibles.
... [propget] hresult columnheadercells( [out, size_is(, ncolumnheadercells,)] iunknown cellaccessibles, [out] long ncolumnheadercells ); parameters cellaccessibles pointer to an array of references to cell accessibles.
... the array is allocated by the server.
...And 5 more matches
nsIDragService
nsidragsession getcurrentsession( ) ; void invokedragsession( in nsidomnode adomnode, in nsisupportsarray atransferables, in nsiscriptableregion aregion, in unsigned long aactiontype ); void invokedragsessionwithimage(in nsidomnode adomnode, in nsisupportsarray atransferablearray, in nsiscriptableregion aregion, in unsigned long aactiontype, in nsidomnode aimage, in long aimagex, in long aimagey, in nsidomdragevent adragevent, in nsidomdatatransfer adatatransfer); void invokedragse...
...ssionwithselection(in nsiselection aselection, in nsisupportsarray atransferablearray, in unsigned long aactiontype, in nsidomdragevent adragevent, in nsidomdatatransfer adatatransfer); void startdragsession( ) ; void suppress(); void unsuppress(); constants constant value description dragdrop_action_none 0 no action.
... invokedragsession() starts a modal drag session with an array of transferables void invokedragsession( in nsidomnode adomnode, in nsisupportsarray atransferables, in nsiscriptableregion aregion, in unsigned long aactiontype ); parameters adomnode the source node on which the drag gesture was started.
...And 5 more matches
nsIEventListenerService
method overview void geteventtargetchainfor(in nsidomeventtarget aeventtarget, [optional] out unsigned long acount, [retval, array, size_is(acount)] out nsidomeventtarget aoutarray); void getlistenerinfofor(in nsidomeventtarget aeventtarget, [optional] out unsigned long acount, [retval, array, size_is(acount)] out nsieventlistenerinfo aoutarray); boolean haslistenersfor(in nsidomeventtarget aeventtarget, in domstring atype); void addsystemeventlistener(in nsidomeventtarget tar...
... obsolete since gecko 7.0 methods geteventtargetchainfor() returns an array of event targets indicating all the targets that will receive the same events that are delivered to the specified target.
...void geteventtargetchainfor( in nsidomeventtarget aeventtarget, [optional] out unsigned long acount, [retval, array, size_is(acount)] out nsidomeventtarget aoutarray ); parameters aeventtarget the nsidomeventtarget for which to return the event target chain.
...And 5 more matches
nsINavHistoryQuery
this is important because, if the user has their profile on a networked drive, query latency can be non-negligible method overview nsinavhistoryquery clone(); void getfolders([optional ]out unsigned long count, [retval,array,size_is(count)] out long long folders); void gettransitions([optional] out unsigned long count, [retval,array,size_is(count)] out unsigned long transitions); void setfolders([const,array, size_is(foldercount)] in long long folders, in unsigned long foldercount); void settransitions([const,array, size_is(count)] in unsigned long transitions, in unsigned long count); attributes attri...
...this attribute must be an array of strings.
...when called as a getter, this returns an array of strings sorted in ascending lexicographical (alphabetical) order.
...And 5 more matches
nsISelectionPrivate
void getrangesforinterval(in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, out pruint32 resultcount, [retval, array, size_is(resultcount)] out nsidomrange results); void getrangesforintervalarray(in nsinode beginnode, in print32 beginoffset, in nsinode endnode, in print32 endoffset, in boolean allowadjacent, in rangearray results); native code only!
... void getrangesforintervalcomarray(in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, in rangearray results); native code only!
... getrangesforinterval() return array of ranges intersecting with the given dom interval.
...And 5 more matches
AnalyserNode.getByteFrequencyData() - Web APIs
the getbytefrequencydata() method of the analysernode interface copies the current frequency data into a uint8array (unsigned byte array) passed into it.
... each item in the array represents the decibel value for a specific frequency.
...for example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 hz.
...And 5 more matches
DOMMatrixReadOnly - Web APIs
dommatrixreadonly.tofloat32array() returns a new float32array containing all 16 elements (m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44) which comprise the matrix.
... the elements are stored into the array as single-precision floating-point numbers in column-major (colexographical access, or "colex") order.
... (in other words, down the first column from top to bottom, then the second column, and so forth.) dommatrixreadonly.tofloat64array() returns a new float64array containing all 16 elements (m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44) which comprise the matrix.
...And 5 more matches
ImageData() - Web APIs
the imagedata() constructor returns a newly instantiated imagedata object built from the typed array given and having the specified width and height.
... syntax new imagedata(array, width [, height]); new imagedata(width, height); parameters array optional a uint8clampedarray containing the underlying pixel representation of the image.
... if no such array is given, an image with a transparent black rectangle of the specified width and height will be created.
...And 5 more matches
WebGL2RenderingContext.getActiveUniforms() - Web APIs
uniformindices an array of gluint specifying the indices of the active uniforms to query.
...possible values: gl.uniform_type: returns an array of glenum indicating the types of the uniforms.
... gl.uniform_size: returns an array of gluint indicating the sizes of the uniforms.
...And 5 more matches
WebGLRenderingContext.bufferData() - Web APIs
syntax // webgl1: void gl.bufferdata(target, size, usage); void gl.bufferdata(target, arraybuffer?
... srcdata, usage); void gl.bufferdata(target, arraybufferview srcdata, usage); // webgl2: void gl.bufferdata(target, arraybufferview srcdata, usage, srcoffset, length); parameters target a glenum specifying the binding point (target).
... possible values: gl.array_buffer: buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data.
...And 5 more matches
Adding 2D content to a WebGL context - Web APIs
gl.bindbuffer(gl.array_buffer, positionbuffer); // now create an array of positions for the square.
...we do this by creating a float32array from the // javascript array, then use it to fill the current buffer.
... gl.bufferdata(gl.array_buffer, new float32array(positions), gl.static_draw); return { position: positionbuffer, }; } this routine is pretty simplistic given the basic nature of the scene in this example.
...And 5 more matches
Signaling and video calling - Web APIs
function sendtooneuser(target, msgstring) { var isunique = true; var i; for (i=0; i<connectionarray.length; i++) { if (connectionarray[i].username === target) { connectionarray[i].send(msgstring); break; } } } this function iterates over the list of connected users until it finds one matching the specified username, then sends the message to that user.
...each entry in connectionarray is a websocket object, so we can just call its send() method directly.
...this involves a change near the end of the "connection" message handler: if (sendtoclients) { var msgstring = json.stringify(msg); var i; if (msg.target && msg.target !== undefined && msg.target.length !== 0) { sendtooneuser(msg.target, msgstring); } else { for (i=0; i<connectionarray.length; i++) { connectionarray[i].send(msgstring); } } } this code now looks at the pending message to see if it has a target property.
...And 5 more matches
Keyed collections - JavaScript
you can use a for...of loop to return an array of [key, value] for each iteration.
... let myset = new set(); myset.add(1); myset.add('some text'); myset.add('foo'); myset.has(1); // true myset.delete('foo'); myset.size; // 2 for (let item of myset) console.log(item); // 1 // "some text" converting between array and set you can create an array from a set using array.from or the spread operator.
... also, the set constructor accepts an array to convert in the other direction.
...And 5 more matches
Working with objects - JavaScript
objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it.
... object.keys(o) this method returns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object o.
... object.getownpropertynames(o) this method returns an array containing all own properties' names (enumerable or not) of an object o.
...And 5 more matches
The arguments object - JavaScript
arguments is an array-like object accessible inside functions that contains the values of the arguments passed to that function.
... note: “array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have array's built-in methods like foreach() or map().
... for example, if a function is passed 3 arguments, you can access them as follows: arguments[0] // first argument arguments[1] // second argument arguments[2] // third argument each argument can also be set or reassigned: arguments[1] = 'new value'; the arguments object is not an array.
...And 5 more matches
Atomics.add() - JavaScript
the static atomics.add() method adds a given value at a given position in the array and returns the old value at that position.
... syntax atomics.add(typedarray, index, value) parameters typedarray an integer typed array.
... one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array.
...And 5 more matches
Atomics.and() - JavaScript
the static atomics.and() method computes a bitwise and with a given value at a given position in the array, and returns the old value at that position.
... syntax atomics.and(typedarray, index, value) parameters typedarray an integer typed array.
... one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array.
...And 5 more matches
Atomics.compareExchange() - JavaScript
the static atomics.compareexchange() method exchanges a given replacement value at a given position in the array, if a given expected value equals the old value.
... syntax atomics.compareexchange(typedarray, index, expectedvalue, replacementvalue) parameters typedarray an integer typed array.
... one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array.
...And 5 more matches
Atomics.exchange() - JavaScript
the static atomics.exchange() method stores a given value at a given position in the array and returns the old value at that position.
... syntax atomics.exchange(typedarray, index, value) parameters typedarray an integer typed array.
... one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array.
...And 5 more matches
Atomics.load() - JavaScript
the static atomics.load() method returns a value at a given position in the array.
... syntax atomics.load(typedarray, index) parameters typedarray an integer typed array.
... one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array.
...And 5 more matches
Atomics.notify() - JavaScript
note: this operation works with a shared int32array only.
... it will return 0 on non-shared arraybuffer objects.
... syntax atomics.notify(typedarray, index, count) parameters typedarray a shared int32array.
...And 5 more matches
Atomics.or() - JavaScript
the static atomics.or() method computes a bitwise or with a given value at a given position in the array, and returns the old value at that position.
... syntax atomics.or(typedarray, index, value) parameters typedarray an integer typed array.
... one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array.
...And 5 more matches
Atomics.sub() - JavaScript
the static atomics.sub() method substracts a given value at a given position in the array and returns the old value at that position.
... syntax atomics.sub(typedarray, index, value) parameters typedarray an integer typed array.
... one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array.
...And 5 more matches
Atomics.xor() - JavaScript
the static atomics.xor() method computes a bitwise xor with a given value at a given position in the array, and returns the old value at that position.
... syntax atomics.xor(typedarray, index, value) parameters typedarray an integer typed array.
... one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array.
...And 5 more matches
Function.prototype.bind() - JavaScript
// does not work with `new (funca.bind(thisarg, args))` if (!function.prototype.bind) (function(){ var slice = array.prototype.slice; function.prototype.bind = function() { var thatfunc = this, thatarg = arguments[0]; var args = slice.call(arguments, 1); if (typeof thatfunc !== 'function') { // closest thing possible to the ecmascript 5 // internal iscallable function throw new typeerror('function.prototype.bind - ' + 'what is trying to be bound is not callable'); ...
... // yes, it does work with `new (funca.bind(thisarg, args))` if (!function.prototype.bind) (function(){ var arrayprototypeslice = array.prototype.slice; function.prototype.bind = function(otherthis) { if (typeof this !== 'function') { // closest thing possible to the ecmascript 5 // internal iscallable function throw new typeerror('function.prototype.bind - what is trying to be bound is not callable'); } var baseargs= arrayprototypeslice.call(arguments, 1), baseargsle...
...s.prototype) { // function.prototype doesn't have a prototype property fnop.prototype = this.prototype; } fbound.prototype = new fnop(); return fbound; }; })(); some of the many differences (there may well be others, as this list does not seriously attempt to be exhaustive) between this algorithm and the specified algorithm are: the partial implementation relies on array.prototype.slice(), array.prototype.concat(), function.prototype.call() and function.prototype.apply(), built-in methods to have their original values.
...And 5 more matches
Porting the Library Detector - Archive of obsolete content
the bulk of the script is an array of test objects, one for each library.
...when this is triggered, the testlibraries() function builds an array of libraries by iterating through the tests and adding an entry for each library which passes.
...however, instead of maintaining its own state by listening for gbrowser events and updating the user interface, the content script will just run when it's loaded, collect the array of library names, and post it back to main.js: function testlibraries() { var win = unsafewindow; var librarylist = []; for(var i in ld_tests) { var passed = ld_tests[i].test(win); if (passed) { var libraryinfo = { name: i, version: passed.version }; librarylist.push(libraryinfo); } } self.postmessage(librarylist); } testlibraries(); mai...
...And 4 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
the new way to do this is to use javascript typed arrays.
... specify "arraybuffer" as your data type to get one from your xmlhttprequest.
... to access that data you're going to need a data view to look at your typed array with.
...And 4 more matches
Supporting search suggestions in search plugins - Archive of obsolete content
your server should then decide upon the suggestions to offer using whatever means it sees fit, and return a json array of results: query string the first element in the array is the original query string.
... completion list an array of suggested search terms.
... the array should be enclosed in square brackets.
...And 4 more matches
Reading from Files - Archive of obsolete content
var lines = []; while(stream.available()) lines.push(stream.readline()); in this example, each line from a stream is read and added to an array.
... the result is an array containing each of the lines in the file.
...an additional method that is useful here is the readbytearray method.
...And 4 more matches
Adding Methods to XBL-defined Elements - Archive of obsolete content
elements with an xbl behavior attached to them have a special property which holds an array of the anonymous child elements inside it.
... each element of the array stores each direct child element of the xbl-defined element.
...the function returns an array of elements, which is the anonymous content.
...And 4 more matches
New in JavaScript 1.3 - Archive of obsolete content
changed functionality in javascript 1.3 changes to date to conform with ecma-262 new constructor date(year, month, day, [,hours [, minutes [, seconds [, milliseconds ]]]]) additional method parameters: setmonth(month[, date]) sethours(hours[, min[, sec[, ms]]]) setminutes(min[, sec[, ms]]) setseconds(sec[, ms]) the length of an array (property length) is now an unsigned, 32-bit integer.
... array.prototype.push(): in javascript 1.2, the push method returned the last element added to an array.
... under javascript 1.3, push returns the new length of the array.
...And 4 more matches
Storing the information you need — Variables - Learn web development
arrays an array is a single object that contains multiple values enclosed in square brackets and separated by commas.
... try entering the following lines into your console: let mynamearray = ['chris', 'bob', 'jim']; let mynumberarray = [10, 15, 40]; once these arrays are defined, you can access each value by their location within the array.
... try these lines: mynamearray[0]; // should return 'chris' mynumberarray[2]; // should return 40 the square brackets specify an index value corresponding to the position of the value you want returned.
...And 4 more matches
source-editor.jsm
retoffset(); object getcaretposition(); object getselection(); void setcaretoffset(number aoffset); void setcaretposition(number aline, [optional] number acolumn, [optional] number aalign); void setselection(number astart, number aend); breakpoint management void addbreakpoint(number alineindex, [optional] string acondition); array getbreakpoints(); boolean removebreakpoint(number alineindex); properties attribute type description dirty boolean set this value to false whenever you save the text; the editor will update it to true when the content is changed.
... getbreakpoints returns an array of all of the breakpoints currently set on the code in the editor instance.
... array getbreakpoints(); parameters none.
...And 4 more matches
JSProtoKey
mxr search for jsproto_null jsproto_object object mxr search for jsproto_object jsproto_function function mxr search for jsproto_function jsproto_array array mxr search for jsproto_array jsproto_boolean boolean mxr search for jsproto_boolean jsproto_json json mxr search for jsproto_json jsproto_date date mxr search for jsproto_date jsproto_math math mxr search for jsproto_math jsproto_number number mxr search for jsproto_number jsproto_string ...
...ntaxerror syntaxerror mxr search for jsproto_syntaxerror jsproto_typeerror typeerror mxr search for jsproto_typeerror jsproto_urierror urierror mxr search for jsproto_urierror jsproto_iterator iterator mxr search for jsproto_iterator jsproto_stopiteration stopiteration mxr search for jsproto_stopiteration jsproto_arraybuffer arraybuffer mxr search for jsproto_arraybuffer jsproto_int8array int8array mxr search for jsproto_int8array jsproto_uint8array uint8array mxr search for jsproto_uint8array jsproto_int16array int16array mxr search for jsproto_int16array jsproto_uint16array uint16array mxr search for jsproto_uint16array jspro...
...to_int32array int32array mxr search for jsproto_int32array jsproto_uint32array uint32array mxr search for jsproto_uint32array jsproto_float32array float32array mxr search for jsproto_float32array jsproto_float64array float64array mxr search for jsproto_float64array jsproto_uint8clampedarray uint8clampedarray mxr search for jsproto_uint8clampedarray jsproto_proxy proxy mxr search for jsproto_proxy jsproto_weakmap weakmap mxr search for jsproto_weakmap jsproto_map map mxr search for jsproto_map jsproto_set set mxr search for jsproto_set jsproto_dataview dataview mxr search for jsproto_dataview jsproto_symbol symbol added in sp...
...And 4 more matches
JS_DefineFunctions
fs const jsfunctionspec * a null-terminated array of function specifications.
... each element of the array defines an individual function.
... fs is a pointer to the first element of an array of jsfunctionspec records.
...And 4 more matches
JS_DefineProperties
ps const jspropertyspec * pointer to the first element of an array containing names, ids, flags, and getproperty and setproperty method for the properties to create.
... the last array element must contain 0-valued members.
...ps is a pointer to the first element of an array of jspropertyspec structures.
...And 4 more matches
nsICryptoHash
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview acstring finish(in prbool aascii); void init(in unsigned long aalgorithm); void initwithstring(in acstring aalgorithm); void update([const, array, size_is(alen)] in octet adata, in unsigned long alen); void updatefromstream(in nsiinputstream astream, in unsigned long alen); constants hash algorithms these constants are used by the init() method to indicate which hashing function to use.
... exceptions thrown ns_error_invalid_arg indicates that an unsupported algorithm type was passed update() adds an array of data to be hashed to the object.
... void update( [const, array, size_is(alen)] in octet adata, in unsigned long alen ); parameters adata a buffer to calculate the hash over.
...And 4 more matches
nsINavHistoryService
in prtime atime, in nsiuri areferringuri, in long atransitiontype, in boolean aisredirect, in long long asessionid); obsolete since gecko 22.0 nsinavhistoryquery getnewquery(); nsinavhistoryqueryoptions getnewqueryoptions(); nsinavhistoryresult executequery(in nsinavhistoryquery aquery, in nsinavhistoryqueryoptions options); nsinavhistoryresult executequeries([array,size_is(aquerycount)] in nsinavhistoryquery aqueries, in unsigned long aquerycount, in nsinavhistoryqueryoptions options); void querystringtoqueries(in autf8string aquerystring, [array, size_is(aresultcount)] out nsinavhistoryquery aqueries, out unsigned long aresultcount, out nsinavhistoryqueryoptions options); autf8string queriestoquerystring([array, size_is(aquerycount)] in n...
...it executes an array of queries.
... nsinavhistoryresult executequeries( [array,size_is(aquerycount)] in nsinavhistoryquery aqueries, in unsigned long aquerycount, in nsinavhistoryqueryoptions options ); parameters aqueries the queries object.
...And 4 more matches
nsIPlacesView
methods getdragableselection() returns an array of selected nsinavhistoryresultnode objects that can be dragged from the view.
... return value an array of nsinavhistoryresultnode objects.
... getremovableselectionranges() returns an array whose elements are themselves arrays of nsinavhistoryresultnode objects that can be removed from the view.
...And 4 more matches
nsITaggingService
ce;1"] .getservice(components.interfaces.nsitaggingservice); method overview void taguri(in nsiuri auri, in nsivariant atags); void untaguri(in nsiuri auri, in nsivariant atags); nsivariant geturisfortag(in astring atag); nsivariant gettagsforuri(in nsiuri auri, [optional] out unsigned long length, [retval, array, size_is(length)] out wstring atags); attributes attribute type description alltags nsivariant retrieves all tags used to tag uris in the data-base (sorted by name).
... atags array of tags to set for the given uri.
... atags array of tags to unset.
...And 4 more matches
Dominators view - Firefox Developer Tools
in particular, allocation stacks are currently only recorded for objects, not for arrays, strings, or internal structures.
... we'll use the monster allocation example, which creates three arrays, each containing 5000 monsters, each monster having a randomly-generated name.
... taking a snapshot to see what it looks like in the dominators view: load the page enable the memory tool in the settings, if you haven't already open the memory tool check "record call stacks" press the button labeled "make monsters!" take a snapshot switch to the "dominators" view analyzing the dominators tree you'll see the three arrays as the top three gc roots, each retaining about 23% of the total memory usage: if you expand an array, you'll see the objects (monsters) it contains.
...And 4 more matches
AudioParam.setValueCurveAtTime() - Web APIs
the curve is a linear interpolation between the sequence of values defined in an array of floating-point values, which are scaled to fit into the given interval starting at starttime and a specific duration.
... syntax var paramref = param.setvaluecurveattime(values, starttime, duration); parameters values an array of floating-point numbers representing the value curve the audioparam will change through along the specified duration.
... every value in the array must be a finite number; if any value is nan, infinity, or -infinity, a typeerror exception is thrown.
...And 4 more matches
Blob - Web APIs
WebAPIBlob
constructor blob() returns a newly created blob object which contains a concatenation of all of the data in the array passed into the constructor.
... instance methods blob.prototype.arraybuffer() returns a promise that resolves with an arraybuffer containing the entire contents of the blob as binary data.
...for example, to construct a blob from a json string: const obj = {hello: 'world'}; const blob = new blob([json.stringify(obj, null, 2)], {type : 'application/json'}); creating a url representing the contents of a typed array the following code creates a javascript typed array and creates a new blob containing the typed array's data.
...And 4 more matches
Using the CSS Typed Object Model - Web APIs
let's start by adding some css to our example, including a custom property and an inhertable property: p { font-weight: bold; } a { --color: red; color: var(--color); } instead of getting all the properties, we create an array of properties of interest and use the stylepropertymapreadonly.get() method to get each of their values: <p> <a href="https://example.com">link</a> </p> <dl id="regurgitation"></dl> // get the element const myelement = document.queryselector('a'); // get the <dl> we'll be populating const styleslist = document.queryselector('#regurgitation'); // retrieve all computed styles with computed...
...stylemap() const allcomputedstyles = myelement.computedstylemap(); // array of properties we're interested in const ofinterest = ['font-weight', 'border-left-color', 'color', '--color']; // iterate through our properties of interest for ( let i = 0; i < ofinterest.length; i++ ) { // properties const cssproperty = document.createelement('dt'); cssproperty.appendchild(document.createtextnode(ofinterest[i])); styleslist.appendchild(cssproperty); // values const cssvalue = document.createelement('dd'); cssvalue.appendchild(document.createtextnode( allcomputedstyles.get(ofinterest[i]))); styleslist.appendchild(cssvalue); } we included border-left-color to demonstrate that, had we included all the properties, every value that defaults to currentcolor (including caret-color, ou...
...try adding some css, such as a width for this paragraph, or adding a css property to the ofinterst array.
...And 4 more matches
Timing element visibility with the Intersection Observer API - Web APIs
although many aspects of this example will not match real world usage (in particular, the articles all have the same text and aren't loaded from a database, and there are just a handful of simple text-only ads that are selected from an array), this should provide enough understanding of the api to quickly learn how to apply the intersection observer api to your own site.
...and the threshold is set to an array containing the values 0.0 and 0.75; this will cause our callback to execute whenever a targeted element becomes completely obscured or first starts to become unobscured (intersection ratio 0.0) or passes through 75% visible in either direction (intersection ratio 0.75).
...for each observer, a list of targets that have done so is compiled, and sent to the observer's callback as an array of intersectionobserverentry objects.
...And 4 more matches
SubtleCrypto.exportKey() - Web APIs
otherwise the promise fulfills with an arraybuffer containing the key.
... raw export this example exports an aes key as an arraybuffer containing the bytes for the key.
...*/ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "raw", key ); const exportedkeybuffer = new uint8array(exported); const exportkeyoutput = document.queryselector(".exported-key"); exportkeyoutput.textcontent = `[${exportedkeybuffer}]`; } /* generate an encrypt/decrypt secret key, then set up an event listener on the "export" button.
...And 4 more matches
SubtleCrypto.wrapKey() - Web APIs
return value result is a promise that fulfills with an arraybuffer containing the encrypted exported key.
...*/ async function wrapcryptokey(keytowrap) { // get the key encryption key const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const wrappingkey = await getkey(keymaterial, salt); return window.crypto.subtle.wrapkey( "raw", keytowrap, wrappingkey, "aes-kw" ); } /* generate an encrypt/decrypt secret key, then wrap it.
...*/ async function wrapcryptokey(keytowrap) { // get the key encryption key const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const wrappingkey = await getkey(keymaterial, salt); iv = window.crypto.getrandomvalues(new uint8array(12)); return window.crypto.subtle.wrapkey( "pkcs8", keytowrap, wrappingkey, { name: "aes-gcm", iv: iv } ); } /* generate a sign/verify key pair, then wrap the private key.
...And 4 more matches
WebGLRenderingContext.texImage2D() - Web APIs
syntax // webgl1: void gl.teximage2d(target, level, internalformat, width, height, border, format, type, arraybufferview?
...ge2d(target, level, internalformat, width, height, border, format, type, htmlvideoelement source); void gl.teximage2d(target, level, internalformat, width, height, border, format, type, imagebitmap source); void gl.teximage2d(target, level, internalformat, width, height, border, format, type, imagedata source); void gl.teximage2d(target, level, internalformat, width, height, border, format, type, arraybufferview srcdata, srcoffset); parameters target a glenum specifying the binding point (target) of the active texture.
... rgba unsigned_short_4_4_4_4 4 2 rgba unsigned_short_5_5_5_1 4 2 rgb unsigned_short_5_6_5 3 2 luminance_alpha unsigned_byte 2 2 luminance unsigned_byte 1 1 alpha unsigned_byte 1 1 other possible values in webgl2 for the versions of teximage2d that take an arraybufferview or a glintptr offset sized format base format r bits g bits b bits a bits shared bits color renderable texture filterable r8 red 8 ● ● r8_snorm red s8 ● rg8 rg 8 8 ● ● rg8_snorm r...
...And 4 more matches
WebGLRenderingContext.texSubImage2D() - Web APIs
syntax // webgl 1: void gl.texsubimage2d(target, level, xoffset, yoffset, width, height, format, type, arraybufferview?
...id gl.texsubimage2d(target, level, xoffset, yoffset, width, height, format, type, htmlvideoelement source); void gl.texsubimage2d(target, level, xoffset, yoffset, width, height, format, type, imagebitmap source); void gl.texsubimage2d(target, level, xoffset, yoffset, width, height, format, type, imagedata source); void gl.texsubimage2d(target, level, xoffset, yoffset, width, height, format, type, arraybufferview srcdata, srcoffset); parameters target a glenum specifying the binding point (target) of the active texture.
... xoffset a glint specifying the lower left texel x coordinate of a width-wide by height-wide rectangular subregion of the texture array.
...And 4 more matches
Using textures in WebGL - Web APIs
const level = 0; const internalformat = gl.rgba; const width = 1; const height = 1; const border = 0; const srcformat = gl.rgba; const srctype = gl.unsigned_byte; const pixel = new uint8array([0, 0, 255, 255]); // opaque blue gl.teximage2d(gl.texture_2d, level, internalformat, width, height, border, srcformat, srctype, pixel); const image = new image(); image.onload = function() { gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, level, internalformat, srcformat, srctype, image); // webgl1 has di...
... const texturecoordbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, texturecoordbuffer); const texturecoordinates = [ // front 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, // back 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, // top 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, // bottom 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, // right 0.0, 0.0, 1.0, 0.0, 1...
....0, 1.0, 0.0, 1.0, // left 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, ]; gl.bufferdata(gl.array_buffer, new float32array(texturecoordinates), gl.static_draw); ...
...And 4 more matches
WebGL model view projection - Web APIs
var data = new float32array([ //triangle 1 settings.left, settings.bottom, settings.depth, settings.right, settings.bottom, settings.depth, settings.left, settings.top, settings.depth, //triangle 2 settings.left, settings.top, settings.depth, settings.right, settings.bottom, settings.depth, settings.right, settings.top, settings.depth ]); // use webgl to draw this onto the ...
... // performance note: creating a new array buffer for every draw call is slow.
... var gl = this.gl; // create a buffer and bind the data var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, data, gl.static_draw); // setup the pointer to our attribute data (the triangles) gl.enablevertexattribarray(this.positionlocation); gl.vertexattribpointer(this.positionlocation, 3, gl.float, false, 0, 0); // setup the color uniform that will be shared across all triangles gl.uniform4fv(this.colorlocation, settings.color); // draw the triangles to the screen gl.drawarrays(gl.triangles, 0, 6); } the shaders are the bits of code written in glsl that take our data points and ultimately render them to the screen.
...And 4 more matches
Using IIR filters - Web APIs
both of these parameters are arrays, neither of which can be larger than 20 items.
... we need to create three arrays.
... one of frequency values for which we want to receive the magnitude response and phase response for, and two empty arrays to receive the data.
...And 4 more matches
Atomics.store() - JavaScript
the static atomics.store() method stores a given value at the given position in the array and returns that value.
... syntax atomics.store(typedarray, index, value) parameters typedarray an integer typed array.
... one of int8array, uint8array, int16array, uint16array, int32array, uint32array, bigint64array, or biguint64array.
...And 4 more matches
Atomics.wait() - JavaScript
the static atomics.wait() method verifies that a given position in an int32array still contains a given value and if so sleeps, awaiting a wakeup or a timeout.
... note: this operation only works with a shared int32array and may not be allowed on the main thread.
... syntax atomics.wait(typedarray, index, value[, timeout]) parameters typedarray a shared int32array.
...And 4 more matches
DataView - JavaScript
the dataview view provides a low-level interface for reading and writing multiple number types in a binary arraybuffer, without having to care about the platform's endianness.
... var littleendian = (function() { var buffer = new arraybuffer(2); new dataview(buffer).setint16(0, 256, true /* littleendian */); // int16array uses the platform's endianness.
... return new int16array(buffer)[0] === 256; })(); console.log(littleendian); // true or false 64-bit integer values because javascript does not currently include standard support for 64-bit integer values, dataview does not offer native 64-bit operations.
...And 4 more matches
Object - JavaScript
object.entries() returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties.
... object.getownpropertynames() returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
... object.getownpropertysymbols() returns an array of all symbol properties found directly upon a given object.
...And 4 more matches
Promise.all() - JavaScript
the promise.all() method takes an iterable of promises as an input, and returns a single promise that resolves to an array of the results of the input promises.
... syntax promise.all(iterable); parameters iterable an iterable object such as an array.
... fulfillment the returned promise is fulfilled with an array containing all the values of the iterable passed as argument (also non-promise values).
...And 4 more matches
Planned changes to shared memory - JavaScript
there is standardization work ongoing that enables developers to create sharedarraybuffer objects again, but changes are needed in order to be use these across threads (i.e., postmessage() for sharedarraybuffer objects throws by default).
... for top-level documents, two headers will need to be set: cross-origin-opener-policy with same-origin as value (protects your origin from attackers) cross-origin-embedder-policy with require-corp as value (protects victims from your origin) with these two headers set, postmessage() will no longer throw for sharedarraybuffer objects and shared memory across threads is therefore available.
... sharedarraybuffer objects are in principle always available, but unfortunately the constructor on the global object is hidden, unless the two headers mentioned above are set, for compatibility with web content.
...And 4 more matches
for...in - JavaScript
objects created from built–in constructors like array and object have inherited non–enumerable properties from object.prototype and string.prototype, such as string's indexof() method or object's tostring() method.
... array iteration and for...in note: for...in should not be used to iterate over an array where the index order is important.
... array indexes are just enumerable properties with integer names and are otherwise identical to general object properties.
...And 4 more matches
simple-storage - Archive of obsolete content
to store a value, just assign it to a property on storage: var ss = require("sdk/simple-storage"); ss.storage.myarray = [1, 1, 2, 3, 5, 8, 13]; ss.storage.myboolean = true; ss.storage.mynull = null; ss.storage.mynumber = 3.1337; ss.storage.myobject = { a: "foo", b: { c: true }, d: null }; ss.storage.mystring = "o frabjous day!"; you can store array, boolean, number, object, null, and string values.
... constructing arrays be careful to construct array objects conditionally in your code, or you may zero them each time the construction code runs.
... of pages the user visits: var ss = require("sdk/simple-storage"); ss.storage.pages = []; require("sdk/tabs").on("ready", function(tab) { ss.storage.pages.push(tab.url); }); require("sdk/ui/button/action").actionbutton({ id: "read", label: "read", icon: "./read.png", onclick: function() { console.log(ss.storage.pages); } }); but this isn't going to work, because it empties the array each time the add-on runs (for example, each time firefox is started).
...And 3 more matches
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
these classes must now be created using xpcom: // nsisupportsarray is bad!
...use nsiarray instead.
... (see xpcom:arrays.) nscomptr<nsisupportsarray> array; - rv = ns_newisupportsarray(getter_addrefs(array)); + array = do_createinstance(ns_supportsarray_contractid); - nscomptr<nsiinputstream> rawstream;- rv = ns_newbyteinputstream(getter_addrefs(rawstream),- (const char*)data, length); + nscomptr<nsistringinputstream> rawstream =+ do_createinstance(ns_stringinputstream_contractid, &rv);+ ns_ensure_success(rv, rv);++ rv = rawstream->setdata((const char*)data, length); ns_ensure_success(rv, rv); nsistringinputstream is not frozen (and thus, not available in the gecko sdk as currently published).
...And 3 more matches
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" }; jsontodom.defaultnamespace = jsontodom.namespaces.html; function jsontodom(jsontemplate, doc, nodes) { function namespace(name) { var reelemnameparts = /^(?:(.*):)?(.*)$/.exec(name); return { namespace: jsontodom.namespaces[reelemnameparts[1]], shortname: reelemnameparts[2] }; } // note that 'elemnameorarray' is: either the full element name (eg.
... [html:]div) or an array of elements in json notation function tag(elemnameorarray, elemattr) { // array of elements?
... if (array.isarray(elemnameorarray)) { var frag = doc.createdocumentfragment(); array.foreach(arguments, function(thiselem) { frag.appendchild(tag.apply(null, thiselem)); }); return frag; } // single element?
...And 3 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
userinfo.envuser = getenv("username"); // username userinfo.envhome = getenv("home"); // user home directory var ldaphost = "example.com"; var ldapbase = "dc=company,dc=local"; if( userinfo.envuser ) { var ldapfilter = "samaccountname=" + userinfo.envuser; } else { throw("couldn't get uid from the environment"); } // ldap attributes to retrieve from the server var ldapattrs = new array( "cn", "mail", "samaccountname" ); // add more attributes here, if needed) // define how to process ldap results before we make the call function processldapvalues(queryresults) { if( queryresults ) { // build the userinfo object for later use for( var attr in ldapattrs ) { userinfo[ ldapattrs[attr] ] = getldapvalue( queryresults, ldapattrs[attr] ); } } else { throw( "n...
...o ldap results" ); } } // call upon ldap for the values in ldapattrs array, // uses the previous processldapvalues() getldapattributes( ldaphost, ldapbase, ldapfilter, ldapattrs.join(",") ); // create account // see also http://blog.deanandadie.net/2010/06/easy-thunderbird-account-management-using-mcd/ // identity defaultpref("mail.identity.id1.fullname", userinfo.cn ); defaultpref("mail.identity.id1.smtpserver", "smtp1" ); defaultpref("mail.identity.id1.useremail", userinfo.mail ); // imap server settings defaultpref("mail.server.server1.hostname", "myimap.server.com" ); defaultpref("mail.server.server1.name", userinfo.mail ); defaultpref("mail.server.server1.port", 993 ); defaultpref("mail.server.server1.sockettype", 3 ); defaultpref("mail.server.server1.type", "imap" ); defaultpref("mail...
... the option --disable-crashreporter is necessary if you get compile error at this stage of the build gmake[7]: entering directory `/usr/local/moz2/commsrc/mozilla/toolkit/crashreporter/google-breakpad/src/common/linux' dump_symbols.cc build then start building [root@b008-02 commsrc]# time make -f client.mk build rm -f ../../mozilla/dist/bin/testcookie if test -f ../../mozilla/dist/bin/testtarray; then cp ../../mozilla/dist/bin/testtarray ../../mozilla/dist/bin/testcookie; fi; gmake[5]: quittant le répertoire « /usr/local/moz/commsrc/mail/app » gmake[4]: quittant le répertoire « /usr/local/moz/commsrc/mail » gmake[3]: quittant le répertoire « /usr/local/moz/commsrc » gmake[2]: quittant le répertoire « /usr/local/moz/commsrc » make[1]: quittant le rép...
...And 3 more matches
New in JavaScript 1.2 - Archive of obsolete content
arrays can now be created using literal notation (inspired by list literal syntax from python 1.x).
... arguments new properties function.arity new methods array.prototype.concat() array.prototype.slice() string.prototype.charcodeat() string.prototype.concat() string.fromcharcode() string.prototype.match() string.prototype.replace() string.prototype.search() string.prototype.slice() string.prototype.substr() new operators delete equality operators (== and !=) new statements labeled statements switch do...while import export other new features regular expressions signed scripts changed functionality in javascript 1.2 you can now nest functions within functions.
... array.prototype.sort() now works on all platforms.
...And 3 more matches
Useful string methods - Learn web development
in each exercise below, we have an array of strings, and a loop that processes each value in the array and displays it in a bulleted list.
... you don't need to understand arrays or loops right now — these will be explained in future articles.
... filtering greeting messages in the first exercise we'll start you off simple — we have an array of greeting card messages, but we want to sort them to list just the christmas messages.
...And 3 more matches
JavaScript object basics - Learn web development
the syntax always follows this pattern: const objectname = { member1name: member1value, member2name: member2value, member3name: member3value }; the value of an object member can be pretty much anything — in our person object we've got a string, a number, two arrays, and two functions.
...sending a single object is much more efficient than sending several items individually, and it is easier to work with than an array, when you want to identify individual items by name.
...next you write a dot, then the item you want to access — this can be the name of a simple property, an item of an array property, or a call to one of the object's methods, for example: person.age person.interests[1] person.bio() sub-namespaces it is even possible to make the value of an object member another object.
...And 3 more matches
Componentizing our React app - Learn web development
since we have more than one task, an array of objects would work well in representing this data.
...the final line of src/index.js should read like this: reactdom.render(<app tasks={data} />, document.getelementbyid("root")); this array is now available to the app component as props.tasks.
... rendering with iteration to render our array of objects, we have to turn each one into a <todo /> component.
...And 3 more matches
HTMLIFrameElement.sendTouchEvent()
x an array of numbers representing the x position of each touch point relative to the browser <iframe>'s visible area in css pixels.
... y an array of numbers representing the y position of each touch point relative to the browser <iframe>'s visible area in css pixels.
... rx an array of numbers representing the x radius of each touch point in css pixels.
...And 3 more matches
Http.jsm
httprequest supports the following parameters: name meaning headers an array of headers postdata this can be: a string: send it as is an array of parameters: encode as form values null/undefined: no post data.
... headers or post data are given as an array of arrays, for each inner array the first value is the key and the second is the value.
...postdata can be of 2 different types: a string or an array of parameters.
...And 3 more matches
L20n Javascript API
ctx.localize(['hello', 'new'], function(l10n) { var node = document.queryselector('[data-l10n-id=hello]'); node.textcontent = l10n.entities.hello.value; node.classlist.remove('hidden'); }); ctx.registerlocales(defaultlocale: string?, availablelocales: array<string>?) register the default locale of the context instance, as well as all other locales available to the context instance before the language negotiation.
... availablelocales is an array of all locales available to the context instance.
... this array (with defaultlocale appended to it if it is not already present) will be used to negotiate the fallback chain for the user.
...And 3 more matches
JSFunctionSpec
this no longer guarantees anything about the vp array.
...an application typically has an array of jsfunctionspec to define all the functions for an object and calls js_definefunctions or js_initclass to create the functions and assign them to an object.
... jsfunctionspec can also be used to define an array element rather than a named property.
...And 3 more matches
JS_Enumerate
get an array of the enumerable properties of a given object.
... syntax jsidarray * js_enumerate(jscontext *cx, js::handleobject obj); name type description cx jscontext * the context in which to enumerate object properties.
...on success, js_enumerate returns a pointer to the first element of an array of property ids.
...And 3 more matches
nsIContentPrefService2
void getbysubdomainandname(in astring domain, in astring name, in nsiloadcontext context, in nsicontentprefcallback2 callback); nsicontentpref getcachedbydomainandname(in astring domain, in astring name, in nsiloadcontext context); void getcachedbysubdomainandname(in astring domain, in astring name, in nsiloadcontext context, out unsigned long len, [retval,array,size_is(len)] out nsicontentpref prefs); nsicontentpref getcachedglobal(in astring name, in nsiloadcontext context); void getglobal(in astring name, in nsiloadcontext context, in nsicontentprefcallback2 callback); void removealldomains(in nsiloadcontext context, [optional] in nsicontentprefcallback2 callback); void removeallglobals(i...
...the preferences are returned in an array through the out-parameter.
... if a preference for a particular subdomain is known not to exist, then an object corresponding to that preference will be present in the array, and, as with getcachedbydomainandname(), its value attribute will be undefined.
...And 3 more matches
nsIDOMMozNetworkStatsManager
to know in advance which kind of origin is available, the moznetworkstatsmanager.getavailablenetworks method returns an array of interfaces.
...to know in advance which kind of origin is available, the moznetworkstatsmanager.getavailablenetworks method returns an array of interfaces.
...to know in advance which kind of origin is available, the moznetworkstatsmanager.getavailablenetworks method returns an array of interfaces.
...And 3 more matches
nsIMsgDBHdr
void markflagged(in boolean flagged); void markhasattachments(in boolean hasattachments); void setprioritystring(in string priority); unsigned long orflags(in unsigned long flags); unsigned long andflags(in unsigned long flags); void setreferences(in string references); acstring getstringreference(in long refnum); void setrecipientsarray(in string names, in string addresses,in unsigned long numaddresses); void setcclistarray(in string names, in string addresses,in unsigned long numaddresses); void setbcclistarray(in string names, in string addresses,in unsigned long numaddresses);new in thunderbird 3.1 [noscript] void getauthorcollationkey(out octetptr key, out unsigned long len); [noscript] vo...
...the value here will effectively be the unparsed header content; it may be easier to set this using setrecipientsarray.
... setrecipientsarray() uses the header parser to recreate the recipients header from an array of names and addresses.
...And 3 more matches
Component; nsIPrefBranch
oolean getboolpref(in string aprefname, requires gecko 54 [optional] in boolean adefaultvalue); string getcharpref(in string aprefname,requires gecko 54 [optional] in string adefaultvalue); requires gecko 58 utf8tring getstringpref(in string aprefname, [optional] in utf8string adefaultvalue); void getchildlist(in string astartingat, [optional] out unsigned long acount, [array, size_is(acount), retval] out string achildarray); void getcomplexvalue(in string aprefname, in nsiidref atype, [iid_is(atype), retval] out nsqiresult avalue); long getintpref(in string aprefname,requires gecko 54 [optional] in long adefaultvalue); long getpreftype(in string aprefname); void lockpref(in string aprefname); boolean prefhasuservalue(in st...
... getchildlist() returns an array of strings representing the child preferences of the root of this branch.
... (to call from javascript use children = nsiprefbranch.getchildlist("",obj), which will fill in obj.value with the count and return an array of keys!
...And 3 more matches
CData
note: this is never ctypes.void_t or an array type with an unspecified length.
... methods available on string objects these methods must be called on objects that are arrays or pointers to 8-bit or 16-bit character or integer types, terminated by a null character.
... readstring() converts a character array to a javascript string.
...And 3 more matches
StructType
fields optional an array of field descriptors, describing all the entries in the structure.
... describing fields the fields array is comprised of field descriptors, one for each field in the structure.
...a complete field descriptor list might look like this: [ {'serialnumber': ctypes.int}, {'username': ctypes.char.ptr} ] properties property type description fields ctype[] a sealed array of field descriptors.
...And 3 more matches
Debugger.Object - Firefox Developer Tools
for example: function h() { var i = function() {}; // display name: h/i f(function () {}); // display name: h/< } var s = f(function () {}); // display name: s< parameternames if the referent is a debuggee function, the names of the its parameters, as an array of strings.
... if the referent is a host function for which parameter names are not available, return an array with one element per parameter, each of which is undefined.
... if the referent is a function proxy, return an empty array.
...And 3 more matches
AnalyserNode.getByteTimeDomainData() - Web APIs
the getbytetimedomaindata() method of the analysernode interface copies the current waveform, or time-domain, data into a uint8array (unsigned byte array) passed into it.
... if the array has fewer elements than the analysernode.fftsize, excess elements are dropped.
... syntax const audioctx = new audiocontext(); const analyser = audioctx.createanalyser(); const dataarray = new uint8array(analyser.fftsize); // uint8array should be the same length as the fftsize analyser.getbytetimedomaindata(dataarray); // fill the uint8array with data returned from getbytetimedomaindata() parameters array the uint8array that the time domain data will be copied to.
...And 3 more matches
AnalyserNode.getFloatTimeDomainData() - Web APIs
the getfloattimedomaindata() method of the analysernode interface copies the current waveform, or time-domain, data into a float32array array passed into it.
... if the array has fewer elements than the analysernode.fftsize, excess elements are dropped.
... syntax var audioctx = new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray = new float32array(analyser.fftsize); // float32array needs to be the same length as the fftsize analyser.getfloattimedomaindata(dataarray); // fill the float32array with data returned from getfloattimedomaindata() parameters array the float32array that the time domain data will be copied to.
...And 3 more matches
AnalyserNode - Web APIs
analysernode.getfloatfrequencydata() copies the current frequency data into a float32array array passed into it.
... analysernode.getbytefrequencydata() copies the current frequency data into a uint8array (unsigned byte array) passed into it.
... analysernode.getfloattimedomaindata() copies the current waveform, or time-domain, data into a float32array array passed into it.
...And 3 more matches
BaseAudioContext.createIIRFilter() - Web APIs
syntax var iirfilter = audiocontext.createiirfilter(feedforward, feedback); parameters feedforward an array of floating-point values specifying the feedforward (numerator) coefficients for the transfer function of the iir filter.
... the maximum length of this array is 20, and at least one value must be nonzero.
... feedback an array of floating-point values specifying the feedback (denominator) coefficients for the transfer function of the iir filter.
...And 3 more matches
CanvasRenderingContext2D.setLineDash() - Web APIs
it uses an array of values that specify alternating lengths of lines and gaps which describe the pattern.
... note: to return to using solid lines, set the line dash list to an empty array.
... syntax ctx.setlinedash(segments); parameters segments an array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units).
...And 3 more matches
Crypto.getRandomValues() - Web APIs
the array given as the parameter is filled with random numbers (random in its cryptographic meaning).
... syntax typedarray = cryptoobj.getrandomvalues(typedarray); parameters typedarray an integer-based typedarray, that is an int8array, a uint8array, an int16array, a uint16array, an int32array, or a uint32array.
... all elements in the array are overwritten with random numbers.
...And 3 more matches
Using the Gamepad API - Web APIs
the index property also functions as the index into the array returned by navigator.getgamepads().
... the navigator.getgamepads() method returns an array of all devices currently visible to the webpage, as gamepad objects (the first value is always null, so null will be returned if there are no gamepads connected.) this can then be used to get the same information.
... buttons: an array of gamepadbutton objects representing the buttons present on the device.
...And 3 more matches
Basic concepts - Web APIs
a key can be one of the following types: string, date, float, a binary blob, and array.
... for arrays, the key can range from an empty value to infinity.
... and you can include an array within an array.
...And 3 more matches
Recording a media element - Web APIs
line 3 creates an empty array, data, which will be used to hold the blobs of media data provided to our ondataavailable event handler.
...the event handler simply pushes the blob onto the data array.
...once that resolves, the array data is returned by startrecording() to its caller.
...And 3 more matches
MediaTrackConstraints - Web APIs
properties of all media tracks deviceid a constraindomstring object specifying a device id or an array of device ids which are acceptable and/or required.
... groupid a constraindomstring object specifying a group id or an array of group ids which are acceptable and/or required.
...this is either an object in the form { x:value, y:value } or an array of such objects, where value is a double-precision integer.
...And 3 more matches
Microdata DOM API - Web APIs
the propertynodelist object can be used to obtain all the values at once usingits getvalues method, which returns an array of all the values.
...nameditem(domstring name); // shadows inherited nameditem() readonly attribute domstring[] names; }; typedef sequence<any> propertyvaluearray; interface propertynodelist : nodelist { propertyvaluearray getvalues(); }; collection .
...names returns an array with the property names of the elements in the collection.
...And 3 more matches
RTCRtpCapabilities - Web APIs
the rtcrtpcapabilities dictionary is a data type used to describe the capabilities of an rtcrtpsender or rtcrtpreceiver in response to a call to the rtcrtpsender.getcapabilities() or rtcrtpreceiver.getcapabilities() static functions, both of which return an array of rtcrtpcapabilities objects.
... an rtcrtpcapabilities object contains an array of objects conforming to rtcrtpcodeccapability (each describing the capabilities of one codec) and an array of the supported rtp header extensions for that codec.
... properties codecs an array of rtcrtpcodeccapability objects, each describing one of the codecs supported by the rtcrtpsender or rtcrtpreceiver.
...And 3 more matches
SubtleCrypto.deriveBits() - Web APIs
the derivebits() method of the subtlecrypto interface can be used to derive an array of bits from a base key.
...it returns a promise which will be fulfilled with an arraybuffer containing the derived bits.
... this method is very similar to subtlecrypto.derivekey(), except that derivekey() returns a cryptokey object rather than an arraybuffer.
...And 3 more matches
Vibration API - Web APIs
the pattern may consist of either a single integer, describing the number of milliseconds to vibrate, or an array of integers describing a pattern of vibrations and pauses.
... a single vibration you may pulse the vibration hardware one time by specifying either a single value or an array consisting of only one value: window.navigator.vibrate(200); window.navigator.vibrate([200]); both of these examples vibrate the device for 200 ms.
... vibration patterns an array of values describes alternating periods in which the device is vibrating and not vibrating.
...And 3 more matches
WebGL2RenderingContext.getBufferSubData() - Web APIs
the webgl2renderingcontext.getbuffersubdata() method of the webgl 2 api reads data from a buffer binding point and writes them to an arraybuffer or sharedarraybuffer.
... syntax void gl.getbuffersubdata(target, srcbyteoffset, arraybufferview dstdata, optional dstoffset, optional length); parameters target a glenum specifying the binding point (target).
... possible values: gl.array_buffer: buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data.
...And 3 more matches
WebGL2RenderingContext.vertexAttribIPointer() - Web APIs
the webgl2renderingcontext.vertexattribipointer() method of the webgl 2 api specifies integer data formats and locations of vertex attributes in a vertex attributes array.
... type a glenum specifying the data type of each component in the array.
... offset a glintptr specifying an offset in bytes of the first component in the vertex attribute array.
...And 3 more matches
WebGLRenderingContext - Web APIs
uniforms and attributes webglrenderingcontext.disablevertexattribarray() disables a vertex attribute array at a given position.
... webglrenderingcontext.enablevertexattribarray() enables a vertex attribute array at a given position.
... webglrenderingcontext.vertexattribpointer() specifies the data formats and locations of vertex attributes in a vertex attributes array.
...And 3 more matches
Lighting in WebGL - Web APIs
building the normals for the vertices the first thing we need to do is generate the array of normals for all the vertices that comprise our cube.
... const normalbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, normalbuffer); const vertexnormals = [ // front 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, // back 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, // top 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, // bottom 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, // right 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, // left -1.0, 0.0, 0.0, ...
... -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0 ]; gl.bufferdata(gl.array_buffer, new float32array(vertexnormals), gl.static_draw); ...
...And 3 more matches
Migrating from webkitAudioContext - Web APIs
in order to port it to the standard audiocontext api: var osc = context.createoscillator(); osc.start(1); osc.stop(1.5); var src = context.createbuffersource(); src.start(1, 0.25); src.stop(2); remove synchronous buffer creation in the old webkit implementation of web audio, there were two versions of createbuffer(), one which created an initially empty buffer, and one which took an existing arraybuffer containing encoded audio, decoded it and returned the result in the form of an audiobuffer.
... the example below shows old code which downloads an audio file over the network, and then decoded it using createbuffer(): var xhr = new xmlhttprequest(); xhr.open("get", "/path/to/audio.ogg", true); xhr.responsetype = "arraybuffer"; xhr.send(); xhr.onload = function() { var decodedbuffer = context.createbuffer(xhr.response, false); if (decodedbuffer) { // decoding was successful, do something useful with the audio buffer } else { alert("decoding the audio buffer failed"); } }; converting this code to use decodeaudiodata() is relatively simple, as can be seen below: var xhr = new xmlhttprequest(); x...
...hr.open("get", "/path/to/audio.ogg", true); xhr.responsetype = "arraybuffer"; xhr.send(); xhr.onload = function() { context.decodeaudiodata(xhr.response, function onsuccess(decodedbuffer) { // decoding was successful, do something useful with the audio buffer }, function onfailure() { alert("decoding the audio buffer failed"); }); }; note that the decodeaudiodata() method is asynchronous, which means that it will return immediately, and then when the decoding finishes, one of the success or failure callback functions will get called depending on whether the audio decoding was successful.
...And 3 more matches
Worker.prototype.postMessage() - Web APIs
transfer optional an optional array of transferable objects to transfer ownership of.
... transferable objects are instances of classes like arraybuffer, messageport or imagebitmap objects that can be transferred.
...as seen above, if you want to pass multiple values you can send an array.
...And 3 more matches
Web APIs
WebAPI
a angle_instanced_arrays abortcontroller abortsignal absoluteorientationsensor abstractrange abstractworker accelerometer addresserrors aescbcparams aesctrparams aesgcmparams aeskeygenparams ambientlightsensor analysernode animation animationeffect animationevent animationplaybackevent animationtimeline arraybufferview attr audiobuffer audiobuffersourcenode audioconfiguration audiocontext audiocontextlatencyca...
...iastreamaudiodestinationnode mediastreamaudiosourcenode mediastreamaudiosourceoptions mediastreamconstraints mediastreamevent mediastreamtrack mediastreamtrackaudiosourcenode mediastreamtrackaudiosourceoptions mediastreamtrackevent mediatrackconstraints mediatracksettings mediatracksupportedconstraints merchantvalidationevent messagechannel messageevent messageport metadata mimetype mimetypearray mouseevent mousescrollevent mousewheelevent mutationevent mutationobserver mutationobserverinit mutationrecord n ndefmessage ndefreader ndefreadingevent ndefrecord ndefwriter namelist namednodemap navigationpreloadmanager navigator navigatorconcurrenthardware navigatorid navigatorlanguage navigatoronline navigatorplugins navigatorstorage networkinformation node nodefilter nodeiterato...
...r nodelist nondocumenttypechildnode notation notification notificationaction notificationevent notifyaudioavailableevent o oes_element_index_uint oes_fbo_render_mipmap oes_standard_derivatives oes_texture_float oes_texture_float_linear oes_texture_half_float oes_texture_half_float_linear oes_vertex_array_object ovr_multiview2 offlineaudiocompletionevent offlineaudiocontext offscreencanvas orientationsensor oscillatornode overconstrainederror p pagetransitionevent paintworklet pannernode parentnode passwordcredential path2d payererrors paymentaddress paymentcurrencyamount paymentdetailsbase paymentdetailsupdate paymentitem paymentmethodchangeevent paymentrequest paymentrequestevent paymentrequestupdateevent paymentresponse paymentvalidationerrors pbkdf2params performance perf...
...And 3 more matches
Warning: JavaScript 1.6's for-each-in loops are deprecated - JavaScript
// 20 } alternative standard syntax you can now use the standard for...in loop to iterate over specified object keys, and get each value inside the loop: var object = { a: 10, b: 20 }; for (var key in object) { var x = object[key]; console.log(x); // 10 // 20 } or, using for...of (es2015) and object.values (es2017), you can get an array of the specified object values and iterate over the array like this: var object = { a: 10, b: 20 }; for (var x of object.values(object)) { console.log(x); // 10 // 20 } array iteration for each...in has been used to iterate over specified array elements.
... deprecated syntax var array = [10, 20, 30]; for each (var x in array) { console.log(x); // 10 // 20 // 30 } alternative standard syntax this is now possible with for...of (es2015) loops as well.
... var array = [10, 20, 30]; for (var x of array) { console.log(x); // 10 // 20 // 30 } iterating over a null-able array for each...in does nothing if the specified value is null or undefined, but for...of will throw an exception in these cases.
...And 3 more matches
TypeError: invalid arguments - JavaScript
the javascript exception "invalid arguments" occurs when typed array constructors are provided with a wrong argument.
... typed array constructors require either a length, another typed array, array-like objects, iterable objects or an arraybuffer object to create a new typed array.
... other constructor arguments will not create a valid typed array.
...And 3 more matches
Map - JavaScript
description a map object iterates its elements in insertion order — a for...of loop returns an array of [key, value] for each iteration.
... iteration methods map.prototype[@@iterator]() returns a new iterator object that contains an array of [key, value] for each element in the map object in insertion order.
... map.prototype.entries() returns a new iterator object that contains an array of [key, value] for each element in the map object in insertion order.
...And 3 more matches
Object.freeze() - JavaScript
as an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array.
... > object.freeze(1) typeerror: 1 is not an object // es5 code > object.freeze(1) 1 // es2015 code an arraybufferview with elements will cause a typeerror, as they are views over memory and will definitely cause other possible issues: > object.freeze(new uint8array(0)) // no elements uint8array [] > object.freeze(new uint8array(1)) // has elements typeerror: cannot freeze array buffer views with elements > object.freeze(new dataview(new arraybuffer(32))) // no elements dataview {} > object.freeze(n...
...ew float64array(new arraybuffer(64), 63, 0)) // no elements float64array [] > object.freeze(new float64array(new arraybuffer(64), 32, 2)) // has elements typeerror: cannot freeze array buffer views with elements note that; as the standard three properties (buf.bytelength, buf.byteoffset and buf.buffer) are read-only (as are those of an arraybuffer or sharedarraybuffer), there is no reason for attempting to freeze these properties.
...And 3 more matches
Symbol.isConcatSpreadable - JavaScript
the symbol.isconcatspreadable well-known symbol is used to configure if an object should be flattened to its array elements when using the array.prototype.concat() method.
...it can control behavior for arrays and array-like objects: for array objects, the default behavior is to spread (flatten) elements.
... for array-like objects, the default behavior is no spreading or flattening.
...And 3 more matches
Iteration protocols - JavaScript
some built-in types are built-in iterables with a default iteration behavior, such as array or map, while other types (such as object) are not.
...{ value: 'bye', done: (this._first = false) } : { done: true } }, _first: true }; }; notice how redefining @@iterator affects the behavior of built-in constructs that use the iteration protocol: console.log([...somestring]); // ["bye"] console.log(somestring + ''); // "hi" iterable examples built-in iterables string, array, typedarray, map, and set are all built-in iterables, because each of their prototype objects implements an @@iterator method.
...ap([[1, 'a'], [2, 'b'], [3, 'c']]).get(2); // "b" let myobj = {}; new weakmap([ [{}, 'a'], [myobj, 'b'], [{}, 'c'] ]).get(myobj); // "b" new set([1, 2, 3]).has(3); // true new set('123').has('2'); // true new weakset(function* () { yield {} yield myobj yield {} }()).has(myobj); // true see also promise.all(iterable) promise.race(iterable) array.from(iterable) syntaxes expecting iterables some statements and expressions expect iterables, for example the for...of loops, the spread operator), yield*, and destructuring assignment: for (let value of ['a', 'b', 'c']) { console.log(value); } // "a" // "b" // "c" console.log([...'abc']); // ["a", "b", "c"] function* gen() { yield* ['a', 'b', 'c']; } console.log(gen().next()); // ...
...And 3 more matches
in operator - JavaScript
syntax prop in object parameters prop a string or symbol representing a property name or array index (non-symbols will be coerced to strings).
... // arrays let trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'] 0 in trees // returns true 3 in trees // returns true 6 in trees // returns false 'bay' in trees // returns false (you must specify the index number, not the value at that index) 'length' in trees // returns true (length is an array property) symbol.iterator in trees // returns true (arrays are iterable, works only in es2015+) // predefined objects 'pi' in math // returns true // custom objects let mycar = {make: 'honda', model: 'accord', year: 1998} 'make' in mycar // returns true 'model' in mycar // re...
... let mycar = {make: 'honda', model: 'accord', year: 1998} delete mycar.make 'make' in mycar // returns false let trees = new array('redwood', 'bay', 'cedar', 'oak', 'maple') delete trees[3] 3 in trees // returns false if you set a property to undefined but do not delete it, the in operator returns true for that property.
...And 3 more matches
places/history - Archive of obsolete content
example let { search } = require("sdk/places/history"); // simple query search( { url: "https://developers.mozilla.org/*" }, { sort: "visitcount" } ).on("end", function (results) { // results is an array of objects containing // data about visits to any site on developers.mozilla.org // ordered by visit count }); // complex query // the query objects are or'd together // let's say we want to retrieve all visits from before a week ago // with the query of 'ruby', but from last week onwards, we want // all results with 'javascript' in the url or title.
...s let lastweek = date.now - (1000*60*60*24*7); search( // first query looks for all entries before last week with 'ruby' [{ query: "ruby", to: lastweek }, // second query searches all entries after last week with 'javascript' { query: "javascript", from: lastweek }], // we want to order chronologically by visit date { sort: "date" } ).on("end", function (results) { // results is an array of objects containing visit data, // sorted by visit date, with all entries from more than a week ago // that contain 'ruby', *in addition to* entries from this last week // that contain 'javascript' }); globals functions search(queries, options) queries can be performed on history entries by passing in one or more query options.
... parameters queries : object|array an object representing a query, or an array of objects representing queries.
...And 2 more matches
stylesheet/style - Archive of obsolete content
stylesheet file url(s) are verified to be local to an add-on, while css rules are verified to be a string or array of strings.
... parameters options : object required options: name type uri string,array a string, or an array of strings, that represents local uri to stylesheet.
... source string,array a string, or an array of strings, that contains css rules.
...And 2 more matches
Using microformats - Archive of obsolete content
get() returns an array of microformat objects corresponding to the microformats found that match specified criteria.
... var microformatsarray = microformats.get(name, rootelement, options, targetarray); parameters name the name of the microformat to find.
... targetarray optional.
...And 2 more matches
Introducing the Audio API extension - Archive of obsolete content
the mozaudioavailable event has 2 attributes: framebuffer: framebuffer (i.e., an array) containing decoded audio sample data (i.e., floats) time: timestamp for these samples measured from the start in seconds the framebuffer contains an array of audio samples.
...you can see an example below: // write samples using a js array var samples = [0.242, 0.127, 0.0, -0.058, -0.242, ...]; var numbersampleswritten = audiooutput.mozwriteaudio(samples); // write samples using a typed array var samples = new float32array([0.242, 0.127, 0.0, -0.058, -0.242, ...]); var numbersampleswritten = audiooutput.mozwriteaudio(samples); in the following example, we create an audio pulse: <!doctype html> <html> <head> <title>genera...
...ting audio in real time</title> <script type="text/javascript"> function playtone() { var output = new audio(); output.mozsetup(1, 44100); var samples = new float32array(22050); for (var i = 0; i < samples.length ; i++) { samples[i] = math.sin( i / 20 ); } output.mozwriteaudio(samples); } </script> </head> <body> <p>this demo plays a one second tone when you click the button below.</p> <button onclick="playtone();">play</button> </body> </html> the mozcurrentsampleoffset() method gives the audible position of the audio stream, meaning the position of the last heard sample.
...And 2 more matches
Java in Firefox Extensions - Archive of obsolete content
ow is now available at http://brett-zamir.me/java_demo/ ] for privileges, the basic procedure is: download and include http://simile.mit.edu/repository/jav...nsionutils.jar within your extension (you can also build your own from the source files at http://simile.mit.edu/repository/jav...xtensionutils/ ) build and add references leading to this jar and all other jars in your extension within an array of java.net.url's, pass to java.net.urlclassloader to get a class loader, and finally pass the classloader and array to a function which gives the necessary privileges: // this function will be called to give the necessary privileges to your jar files // however, the policy never comes into play, because // (1) adding permissions doesn't add to the policy itself, and // (2) addurl alone d...
... to give your extension full privileges var extensionurl = "file:///" + extensionpath.path.replace(/\\/g,"/"); var classloaderjarpath = extensionurl + "/java/javafirefoxextensionutils.jar"; // add the paths for all the other jar files that you will be using var myjarpath = extensionurl + "/java/testjava.jar"; // seems you don't actually have to replace the backslashes as they work as well var urlarray = []; // build a regular javascript array (liveconnect will auto-convert to a java array) urlarray[0] = new java.net.url(myjarpath); urlarray[1] = new java.net.url(classloaderjarpath); var cl = java.net.urlclassloader.newinstance(urlarray); //set security policies using the above policyadd() function policyadd(cl, urlarray); now you can begin using liveconnect, including referencing the c...
...the following is a somewhat simplified snippet from xquseme: var reflect = java.lang.reflect; // build an array of the class types which are expected by our constructor (in this case, java.io.file and a class from another jar we loaded, com.sleepycat.db.environmentconfig) var paramtypes = reflect.array.newinstance(java.lang.class, 2); // 2nd argument should indicate the number of items in following array paramtypes[0] = java.io.file; var envconfigclass = loader.loadclass('com.sleepycat.db.environmentconfig...
...And 2 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
the method returns an array in javascript, and can be called on the document element or other nodes to search only their subtree.
... to get an array of all elements in the dom tree, you can use getelementsbytagname("*").
... document.getelementsbytagname( atagname ) returns an array of elements with the specified name in the document.
...And 2 more matches
Styling a Tree - Archive of obsolete content
(we don't use getrowproperties() as the text color will not be inherited into each cell.) prior to gecko 22 the properties object that is passed as the last argument to the getcellproperties() is an xpcom object that implements nsisupportsarray.
... it is really just an xpcom version of an array.
... it contains a function appendelement() which can be used to add an element to the array.
...And 2 more matches
calICalendarView - Archive of obsolete content
attribute calicalendarviewcontroller controller; void showdate(in calidatetime adate); void setdaterange(in calidatetime astartdate, in calidatetime aenddate); readonly attribute calidatetime startdate; readonly attribute calidatetime enddate; readonly attribute boolean supportsdisjointdates; readonly attribute boolean hasdisjointdates; void setdatelist(in unsigned long acount, [array,size_is(acount)] in calidatetime adates); void getdatelist(out unsigned long acount, [array,size_is(acount),retval] out calidatetime adates); attribute caliitembase selecteditem; attribute calidatetime selectedday; attributes displaycalendar the displaycalendar is an implementation of the calicalendar interface.
...note: this will likely change to selecteditems and return an array of caliitembases in order to support selecting multiple items at once.
...(for instance, calendar-month-view will show all dates from the start of the week of astartdate to the end of the week of aenddate.) setdatelist void setdatelist(in unsigned long acount, [array,size_is(acount)] in calidatetime adates); this function can only be called if supportsdisjointdates is true and will throw an error if it is not.
...And 2 more matches
NPN_GetStringIdentifiers - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary returns an array of opaque identifiers for the names that are passed in.
... syntax #include <npruntime.h> void npn_getstringidentifiers(const nputf8 **names, int32_t namecount, npidentifier *identifiers); parameters the function has the following parameters: names an array of strings for which opaque identifiers should be returned.
... namecount the number of strings in the names array.
...And 2 more matches
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
ecmascript 2016 array.prototype.includes() (firefox 43) typedarray.prototype.includes() (firefox 43) exponentiation operator (firefox 52) ecmascript 2017 object.values() (firefox 47) object.entries() (firefox 47) string.prototype.padstart() (firefox 48) string.prototype.padend() (firefox 48) object.getownpropertydescriptors() (firefox 50) async functions async function (firefox 52) async function ...
...expression (firefox 52) asyncfunction (firefox 52) await (firefox 52) trailing commas in function parameter lists (firefox 52) ecmascript 2018 spread in object literals and rest parameters (firefox 55) for await...of (firefox 57) global_objects/sharedarraybuffer (firefox 57, with flags) global_objects/promise/finally (firefox 58) global_objects/regexp/dotall (not yet implemented; in other browsers) regexp lookbehind assertions (not yet implemented; in other browsers) regexp unicode property escapes (not yet implemented; in other browsers) regexp named capture groups (not yet implemented; in other browsers) ecmascript 2019 array.flat() (firefox 62) array.flatmap() (firefox 62) object.fromentries() (firefox 63) string.trimstart() and string.trimend() (firefox 61) ...
... additions to the arraybuffer object arraybuffer.transfer() (spec) new typedobject objects based on typed objects draft, and exposed via a global typedobject object, e.g.
...And 2 more matches
Generator comprehensions - Archive of obsolete content
a significant drawback of array comprehensions is that they cause an entire new array to be constructed in memory.
... when the input to the comprehension is itself a small array the overhead involved is insignificant — but when the input is a large array or an expensive (or indeed infinite) generator the creation of a new array can be problematic.
...generator comprehensions are syntactically almost identical to array comprehensions — they use parentheses instead of braces— but instead of building an array they create a generator that can execute lazily.
...And 2 more matches
New in JavaScript 1.8.5 - Archive of obsolete content
bug 505587 object.keys() returns an array of all enumerable properties on an object.
... bug 307791 object.getownpropertynames() returns an array of all enumerable and non-enumerable properties on an object.
...bug 492844 array.isarray() checks if a variable is an array.
...And 2 more matches
New in JavaScript 1.8 - Archive of obsolete content
typically you would have to create a custom function which would have a yield in it, but this addition allows you to use array comprehension-like syntax to create an identical generator statement.
... array.prototype.reduce() array.prototype.reduceright() changed functionality in javascript 1.8 changes in destructuring for..in one change that occurred in the release of javascript 1.8 was a bug fix related to the key/value destructuring of arrays introduced in javascript 1.7.
... previously it was possible to destructure the keys/values of an array by using for ( var [key, value] in array ).
...And 2 more matches
Desktop gamepad controls - Game development
epad's currently pressed buttons we will need a function that will do exactly that on every frame: function gamepadupdatehandler() { buttonspressed = []; if(controller.buttons) { for(var b=0; b<controller.buttons.length; b++) { if(controller.buttons[b].pressed) { buttonspressed.push(b); } } } } we first reset the buttonspressed array to get it ready to store the latest info we'll write to it from the current frame.
... then, if the buttons are available we loop through them; if the pressed property is set to true, then we add them to the buttonspressed array for later processing.
...unction: function gamepadbuttonpressedhandler(button) { var press = false; for(var i=0; i<buttonspressed.length; i++) { if(buttonspressed[i] == button) { press = true; } } return press; } the function takes a button as a parameter; in the loop it checks if the given button's number is among the currently pressed buttons available in the buttonspressed array.
...And 2 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
23 array array, codingscripting, glossary, javascript, programming an array is an ordered collection of data (either primitive or object depending upon the language).
... arrays are used to store multiple values in a single variable.
... 27 base64 advanced, base64, javascript, typed arrays, uri, url, unicode problem, atob(), btoa() base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ascii string format by translating it into a radix-64 representation.
...And 2 more matches
Graceful asynchronous programming with Promises - Learn web development
this takes an array of promises as an input parameter and returns a new promise object that will fulfil only if and when all promises in the array fulfil.
...}); if they all fulfil, the chained .then() block's executor function will be passed an array containing all those results as a parameter.
... at the end of the block, we chain on a .catch() call, to handle any error cases that may occur with any of the promises passed in the array to .all().
...And 2 more matches
Gecko info for Windows accessibility vendors
you can then get the number of children via iaccessible::get_accnumchildren(), then allocate an array of variant's to hold the children, and call ienumvariant::next() to get all the children in one call.
...the return value numattribs specifies the number of attributes for this node, and the last 3 parameters return 3 arrays corresponding to attribute name, namespace id, and attribute value.
... hresult get_attributes( /* [in] */ unsigned short maxattribs, /* [out] */ bstr *attribnames, /* [out] */ short *namespaceid, /* [out] */ bstr *attribvalues, /* [out] */ unsigned short *numattribs); a variation on this method is get_attributesfornames, which lets turns the attribnames array into an [in] parameter, letting you specify only those attributes you're interested in.
...And 2 more matches
FileUtils.jsm
to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/fileutils.jsm"); the file constructor if you have a path to a file (or directory) you want to obtain an nsifile for, you can do so using the file constructor, like this: var f = new fileutils.file(mypath); method overview nsifile getfile(string key, array patharray, bool followlinks); nsifile getdir(string key, array patharray, bool shouldcreate, bool followlinks); nsifileoutputstream openfileoutputstream(nsifile file, int modeflags); nsifileoutputstream openatomicfileoutputstream(nsifile file, int modeflags); nsifileoutputstream opensafefileoutputstream(nsifile file, int modeflags); void closeatomicfil...
... nsifile getfile( string key, array patharray, bool followlinks ); parameters key the nsidirectoryservice key to start from (see getting special files for more info) patharray an array of path components to locate beneath the directory specified by key.
... the last item in this array must be the leaf name of a file.
...And 2 more matches
SourceMap.jsm
sources: an array of urls to the original source files.
... names: an array of identifiers that can be referenced by individual mappings.
... chunk: a string snippet of generated js code, another instance of sourcenode, or an array where each member is one of those things.
...And 2 more matches
Sqlite.jsm
this can be an array or an object.
...this argument can be an array of positional parameters or an object of named parameters.
... note: callers are encouraged to pass objects rather than arrays for bound parameters because they prevent foot guns.
...And 2 more matches
Scripting Java
all the methods return an array of file objects.
... creating java arrays rhino provides no special syntax for creating java arrays.
... you must use the java.lang.reflect.array class for this purpose.
...And 2 more matches
Self-hosted builtins in SpiderMonkey
a select set of c++-implemented builtins is installed via the intrinsic_functions array in selfhosting.cpp, as described below.
...of note, it provides implementations of list and record, types defined in the ecmascript specifications that are similar to array and object, but can't be modified by application code.
... to add a self-hosted function as a method to a host object, add it to that host object's jsfunctionspec array using the js_self_hosted_fn macro.
...And 2 more matches
JS_ConvertArguments
converts a series of js values, passed in an argument array, to their corresponding js types.
...obsolete since jsapi 30 this must be an argv pointer created by the js engine and passed to a jsnative or jsfastnative callback, not an array created by application code.
...argv is a pointer to the array of js values to convert.
...And 2 more matches
JS_GetStringChars
description js_getstringchars obsolete since javascript 1.8.5 returns a pointer to the first element of an array of jschars.
... warnings: the array is not necessarily null-terminated.
... the program must not modify the array.
...And 2 more matches
JS_NewExternalString
chars const char16_t * or const jschar * pointer to the first element of an array of char16_ts.
... this array is used as the character buffer of the jsstring to be created.
... the array must be populated with the desired character data before js_newexternalstring is called, and the array must remain in memory, with its contents unchanged, for as long as the javascript engine needs to hold on to it.
...And 2 more matches
JS_PushArguments
convert any number of arguments to jsvals and store the resulting jsvals in an array.
...format is a sequential character array, where each element of the array indicates the js type into which to convert the next c/c++ argument.
...if successful, js_pusharguments would return a pointer to the first element of an array of four jsvals: a boolean, a number, an object (or null), and a boolean.
...And 2 more matches
JSAPI reference
tionforprincipals obsolete since jsapi 28 error handling struct jserrorformatstring added in spidermonkey 17 class jserrorreport class js::autosaveexceptionstate added in spidermonkey 31 enum jsexntype added in spidermonkey 17 js_reporterror js_reportwarning js_reporterrornumber js_reporterrornumberuc js_reporterrorflagsandnumber js_reporterrorflagsandnumberuc js_reporterrornumberucarray added in spidermonkey 24 js_reportoutofmemory js_reportallocationoverflow added in spidermonkey 1.8 js_geterrorreporter js_seterrorreporterobsolete since jsapi 52 js_errorfromexception js_geterrorprototype jsreport_is_exception jsreport_is_strict jsreport_is_warning jsreport_is_strict_mode_error the following functions allow c/c++ functions to throw and catch javascript exceptions: ...
...ermonkey 31 class js::persistentrootedfunction added in spidermonkey 31 class js::persistentrootedscript added in spidermonkey 31 class js::persistentrootedstring added in spidermonkey 31 class js::persistentrootedsymbol added in spidermonkey 38 class js::persistentrootedid added in spidermonkey 31 class js::persistentrootedvalue added in spidermonkey 31 class js::autovaluearray<n> added in spidermonkey 31 class js::autovectorrooter<t> added in spidermonkey 17 class js::autovaluevector added in spidermonkey 17 class js::autoidvector added in spidermonkey 17 class js::autoobjectvector added in spidermonkey 24 class js::autofunctionvector added in spidermonkey 31 class js::autoscriptvector added in spidermonkey 17 class js::handlevaluearray added i...
...uctor added in spidermonkey 1.8.5 js_newglobalobject added in spidermonkey 1.8 js_newobjectwithgivenproto js_new added in spidermonkey 1.8 js_isglobalobject added in jsapi 24 js_constructobject obsolete since jsapi 16 js_constructobjectwitharguments obsolete since jsapi 16 js_getclass js_getobjectprototype added in jsapi 17 js_getfunctionprototype added in spidermonkey 17 js_getarrayprototype added in spidermonkey 24 js_getconstructor js_getglobalforobject js_getinstanceprivate js_getprototype js_setprototype js_getprivate js_setprivate js_freezeobject added in spidermonkey 1.8.5 js_deepfreezeobject added in spidermonkey 1.8.5 js_isextensible added in spidermonkey 1.8.5 js_preventextensions added in spidermonkey 45 js_instanceof js_hasinstance js_isnative added ...
...And 2 more matches
IAccessibleRelation
[propget] hresult targets( [in] long maxtargets, [out, size_is(maxtargets), length_is( ntargets)] iunknown targets, [out] long ntargets ); parameters maxtargets maximum size of the array allocated by the client.
... targets the array of target objects.
... note that this array is to be allocated by the client and freed when no longer needed.
...And 2 more matches
mozIStorageBindingParams
last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports you can only create mozistoragebindingparams objects by calling the mozistoragebindingparamsarray.newbindingparams().
... method overview void bindbyindex(in unsigned long aindex, in nsivariant avalue); void bindblobbyindex(in unsigned long aindex, [array, const, size_is(avaluesize)] in octet avalue, in unsigned long avaluesize); void binddoublebyindex(in unsigned long aindex, in double avalue); native code only!
... void bindbyname(in autf8string aname, in nsivariant avalue); void bindblobbyname(in autf8string aname, [array, const, size_is(avaluesize)] in octet avalue, in unsigned long avaluesize); void binddoublebyname(in autf8string aname, in double avalue); native code only!
...And 2 more matches
mozIStorageConnection
mozistorageasyncstatement createasyncstatement(in autf8string asqlstatement); void createfunction(in autf8string afunctionname, in long anumarguments, in mozistoragefunction afunction); mozistoragestatement createstatement(in autf8string asqlstatement); void createtable(in string atablename, in string atableschema); mozistoragependingstatement executeasync([array, size_is(anumstatements)] in mozistoragebasestatement astatements, in unsigned long anumstatements, [optional] in mozistoragestatementcallback acallback ); void executesimplesql(in autf8string asqlstatement); boolean indexexists(in autf8string aindexname); void preload(); obsolete since gecko 1.9 void removefunction(in autf8string afunctionname); moz...
... executeasync() asynchronously executes an array of queries created with this connection, using any currently bound parameters.
... mozistoragependingstatement executeasync( [array, size_is(anumstatements)] in mozistoragebasestatement astatements, in unsigned long anumstatements, in mozistoragestatementcallback acallback optional ); parameters astatements the array of statements to execute asynchronously.
...And 2 more matches
nsIBinaryOutputStream
inherits from: nsioutputstream last changed in gecko 1.7 method overview void setoutputstream(in nsioutputstream aoutputstream); void write8(in pruint8 abyte); void write16(in pruint16 a16); void write32(in pruint32 a32); void write64(in pruint64 a64); void writeboolean(in prbool aboolean); void writebytearray([array, size_is(alength)] in pruint8 abytes, in pruint32 alength); void writebytes(alength)] in string astring, in pruint32 alength); void writedouble(in double adouble); void writefloat(in float afloat); void writestringz(in string astring); void writeutf8z(in wstring astring); void writewstringz(in wstring astring); methods setoutputstream() sets the stream to which output is dir...
... writebytearray() writes an opaque byte array to the stream.
... void writebytearray( [array, size_is(alength)] in pruint8 abytes, in pruint32 alength ); parameters abytes the bytes to write to the stream.
...And 2 more matches
nsIContentViewManager
method overview void getcontentviewsin(in float axpx, in float aypx, in float atopsize, in float arightsize, in float abottomsize, in float aleftsize, [optional] out unsigned long alength, [retval, array, size_is(alength)] out nsicontentview aresult); attributes attribute type description rootcontentview nsicontentview the root content view.
... methods getcontentviewsin() returns an array of nsicontentview objects representing all of the content views that intersect with the specified rectangle in the browser.
... void getcontentviewsin( in float axpx, in float aypx, in float atopsize, in float arightsize, in float abottomsize, in float aleftsize, out unsigned long alength, optional [retval, array, size_is(alength)] out nsicontentview aresult ); parameters axpx the x coordinate of the anchor point of the rectangle, in css pixels.
...And 2 more matches
nsIDroppedLinkHandler
irefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview boolean candroplink(in nsidomdragevent aevent, in prbool aallowsamedocument); astring droplink(in nsidomdragevent aevent, out astring aname, [optional] in boolean adisallowinherit); void droplinks(in nsidomdragevent aevent, [optional] in boolean adisallowinherit, [optional] out unsigned long acount, [retval, array, size_is(acount)] out nsidroppedlinkitem alinks); methods candroplink() determines if a link being dragged can be dropped.
...if non-empty links array is returned the caller can, for instance, load it.
... if empty links array is returned, there is no valid link to be dropped.
...And 2 more matches
nsIFeed
items nsiarray specifies an array of the items or entries on the feed.
... skipdays nsiarray an array of days of the week on which the feed should not be fetched.
... each entry in the array is the name of one day of the week to skip.
...And 2 more matches
nsIFeedContainer
.idlscriptable this interface provides standard fields used by both feeds (nsifeed) and feed entries (nsifeedentry) 1.0 66 introduced gecko 1.8 inherits from: nsifeedelementbase last changed in gecko 1.8.1 (firefox 2 / thunderbird 2 / seamonkey 1.1) method overview void normalize(); attributes attribute type description authors nsiarray an array of nsifeedperson objects describing the authors of the feed or entry.
... categories nsiarray an array of the categories found in a feed or entry.
... note: the returned array will contain nsifeedcategory objects, except that interface has not been implemented yet.
...And 2 more matches
nsIJumpListBuilder
each list is made up of an array of nsiwinjumplistitems representing items such as shortcuts, links, and separators.
...method overview void abortlistbuild(); boolean addlisttobuild(in short acattype, in nsiarray items optional, in astring catname optional); boolean commitlistbuild(); boolean deleteactivelist(); boolean initlistbuild(in nsimutablearray removeditems); attributes attribute type description available short indicates whether jump list taskbar features are supported by the current host.
...boolean addlisttobuild( in short acattype, in nsiarray items, optional in astring catname optional ); parameters acattype the type of list to add.
...And 2 more matches
nsIProperties
to get an instance, use: var properties = components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties); method overview void get(in string prop, in nsiidref iid, [iid_is(iid),retval] out nsqiresult result); void getkeys(out pruint32 count, [array, size_is(count), retval] out string keys); boolean has(in string prop); void set(in string prop, in nsisupports value); void undefine(in string prop); methods get() gets the xpcom object associated with a particular name.
... getkeys() returns an array of property names.
... nsmemory.h defines the macro ns_free_xpcom_allocated_pointer_array, which can be used to free akeys when it is no longer needed.
...And 2 more matches
nsIStringBundle
method overview wstring formatstringfromid(in long aid, [array, size_is(length)] in wstring params, in unsigned long length); wstring formatstringfromname(in wstring aname, [array, size_is(length)] in wstring params, in unsigned long length); nsisimpleenumerator getsimpleenumeration(); wstring getstringfromid(in long aid); wstring getstringfromname(in wstring aname); methods formatstringfromid() returns a formatte...
...d string with the given id from the string bundle, where each occurrence of %s (uppercase) is replaced by each successive element in the supplied array.
... wstring formatstringfromid( in long aid, [array, size_is(length)] in wstring params, in unsigned long length ); parameters aid the id of the string to retrieve.
...And 2 more matches
nsISyncMessageSender
returns an array containing return values from each listener invoked.
... principal nsiprincipal returns array: an array of structured clones of the objects returned by all the listeners to this message, one element for each listener.
... if there was only one listener, it is an array with a single element.
...And 2 more matches
NS_CStringContainerInit2
adata [in] an array of characters used to initialize the string object.
... adatalength [in] an optional parameter that specifies the length of the array pointed to by adata.
...if this value is zero, then the array referenced by adata (if any) will be copied.
...And 2 more matches
PKCS #11 Netscape Trust Objects - Network Security Services
attribute type description cka_class ck_object_class cko_netscape_trust cka_issuer byte array der-encoding of the certificate issuer name.
... cka_subject byte array der-encoding of the certificate subject name.
... cka_serial_number byte array der-encoding of the certificate serial number.
...And 2 more matches
Aggregate view - Firefox Developer Tools
type this is the default view, which looks something like this: it groups the things on the heap into types, including: javascript objects: such as function or array dom elements: such as htmlspanelement or window strings: listed as "strings" javascript sources: listed as "jsscript" internal objects: such as "js::shape".
... for example, in the screenshot above, you can see that: there are four array objects that account for 15% of the total heap.
...for example, the entry for array tells us that there are four array objects in the snapshot.
...And 2 more matches
Sorting algorithms comparison - Firefox Developer Tools
iteratively (200 iterations) generates a randomized array and calls sort().
... bubblesort() implements a bubble sort, returning the sorted array.
... selectionsort() implements a selection sort, returning the sorted array.
...And 2 more matches
The JavaScript input interpreter - Firefox Developer Tools
you get autocomplete suggestions for array elements, as well: you can enable or disable autocompletion via the settings ("gear") menu in the web console toolbar.
... $$(selector, element) looks up a css selector string selector, returning an array of dom nodes descended from element that match.
...this is like for document.queryselectorall(), but returns an array instead of a nodelist.
...And 2 more matches
AudioBuffer.copyToChannel() - Web APIs
the copytochannel() method of the audiobuffer interface copies the samples to the specified channel of the audiobuffer, from the source array.
... syntax myarraybuffer.copytochannel(source, channelnumber, startinchannel); parameters source a float32array that the channel data will be copied from.
... example var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var anotherarray = new float32array; // copy channel data from second channel of myarraybuffer.
...And 2 more matches
AudioBuffer.getChannelData() - Web APIs
the getchanneldata() method of the audiobuffer interface returns a float32array containing the pcm data associated with the channel, defined by the channel parameter (with 0 representing the first channel).
... syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var nowbuffering = myarraybuffer.getchanneldata(channel); parameters channel the channel property is an index representing the particular channel to get data for.
... return value a float32array.
...And 2 more matches
AudioBuffer - Web APIs
methods audiobuffer.getchanneldata() returns a float32array containing the pcm data associated with the channel, defined by the channel parameter (with 0 representing the first channel).
... audiobuffer.copyfromchannel() copies the samples from the specified channel of the audiobuffer to the destination array.
... audiobuffer.copytochannel() copies the samples to the specified channel of the audiobuffer, from the source array.
...And 2 more matches
BaseAudioContext.decodeAudioData() - Web APIs
the decodeaudiodata() method of the baseaudiocontext interface is used to asynchronously decode audio file data contained in an arraybuffer.
... in this case the arraybuffer is loaded from xmlhttprequest and filereader.
... syntax older callback syntax: baseaudiocontext.decodeaudiodata(arraybuffer, successcallback, errorcallback); newer promise-based syntax: promise<decodeddata> baseaudiocontext.decodeaudiodata(arraybuffer); parameters arraybuffer an arraybuffer containing the audio data to be decoded, usually grabbed from xmlhttprequest, windoworworkerglobalscope.fetch() or filereader.
...And 2 more matches
Cache.matchAll() - Web APIs
WebAPICachematchAll
the matchall() method of the cache interface returns a promise that resolves to an array of all matching responses in the cache object.
... syntax cache.matchall(request, {options}).then(function(response) { // do something with the response array }); parameters request optional the request for which you are attempting to find responses in the cache.
... return value a promise that resolves to an array of all matching responses in the cache object.
...And 2 more matches
Element.querySelectorAll() - Web APIs
e, an attribute selector is used to return a list of the list items contained within a list whose id is "userlist" which have a "data-active" attribute whose value is "1": var container = document.queryselector("#userlist"); var matches = container.queryselectorall("li[data-active='1']"); accessing the matches once the nodelist of matching elements is returned, you can examine it just like any array.
... if the array is empty (that is, its length property is 0), then no matches were found.
... otherwise, you can simply use standard array notation to access the contents of the list.
...And 2 more matches
FileSystemDirectoryReader.readEntries() - Web APIs
the filesystemdirectoryreader interface's readentries() method retrieves the directory entries within the directory being read and delivers them in an array to a provided callback function.
... the objects in the array are all based upon filesystementry.
...the function receives a single input parameter: an array of file system entry objects, each based on filesystementry.
...And 2 more matches
HTMLInputElement - Web APIs
webkitentries array of filesystementry objects: describes the currently selected files or directories.
... files filelist array: returns the list of selected files.
... htmlinputelement.labels read only nodelist array: returns a list of <label> elements that are labels for this element.
...And 2 more matches
ImageData.data - Web APIs
WebAPIImageDatadata
the readonly imagedata.data property returns a uint8clampedarray that contains the imagedata object's pixel data.
... data is stored as a one-dimensional array in the rgba order, with integer values between 0 and 255 (inclusive).
...the data array stores four values for each pixel, making 4 x 10,000, or 40,000 values in all.
...And 2 more matches
Using IndexedDB - Web APIs
the method accepts two parameters: the storenames (the scope, defined as an array of object stores that you want to access) and the mode (readonly or readwrite) for the transaction.
...you can pass an empty array if you want the transaction to span all object stores, but don't do it because the spec says an empty array should generate an invalidaccesserror.
... one common pattern with cursors is to retrieve all objects in an object store and add them to an array, like this: var customers = []; objectstore.opencursor().onsuccess = function(event) { var cursor = event.target.result; if (cursor) { customers.push(cursor.value); cursor.continue(); } else { console.log("got all customers: " + customers); } }; note: alternatively, you can use getall() to handle this case (and getallkeys()) .
...And 2 more matches
IntersectionObserver.thresholds - Web APIs
if only one threshold ratio was provided when instanitating the object, this will be an array containing that single value.
... syntax var thresholds = intersectionobserver.thresholds; value an array of intersection thresholds, originally specified using the threshold property when instantiating the observer.
... if only one observer was specified, without being in an array, this value is a one-entry array containing that threshold.
...And 2 more matches
KeyframeEffect.setKeyframes() - Web APIs
there are two different ways to format keyframes: an array of objects (keyframes) consisting of properties and values to iterate over.
... an object containing key-value pairs consisting of the property to animate and an array of values to iterate over.
... element.animate({ opacity: [ 0, 1 ], // [ from, to ] color: [ "#fff", "#000" ] // [ from, to ] }, 2000); using this format, the number of elements in each array does not need to be equal.
...And 2 more matches
NavigatorPlugins.plugins - Web APIs
returns a pluginarray object, listing the plugin objects describing the plugins installed in the application.
... in firefox 29 and later, enumeration of the navigator.plugins array may be restricted as a privacy measure.
... applications that must check for the presence of a browser plugin should query navigator.plugins or navigator.mimetypes by exact name instead of enumerating the navigator.plugins array and comparing every plugin's name.
...And 2 more matches
NodeList - Web APIs
WebAPINodeList
although nodelist is not an array, it is possible to iterate over it with foreach().
... it can also be converted to a real array using array.from().
... however, some older browsers have not implemented nodelist.foreach() nor array.from().
...And 2 more matches
Using Pointer Events - Web APIs
var ongoingtouches = new array(); when a pointerdown event occurs, indicating that a new touch on the surface has occurred, the handlestart() function below is called.
...neto(" + evt.clientx + ", " + evt.clienty + ");"); ctx.lineto(evt.clientx, evt.clienty); ctx.linewidth = 4; ctx.strokestyle = color; ctx.stroke(); ongoingtouches.splice(idx, 1, copytouch(evt)); // swap in the new touch record log("."); } else { log("can't figure out which touch to continue: idx = " + idx); } } this function looks in our cached touch information array for the previous information about each touch to determine the starting point for each touch's new line segment to be drawn.
... after drawing the line, we call array.splice() to replace the previous information about the touch point with the current information in the ongoingtouches array.
...And 2 more matches
PublicKeyCredentialCreationOptions.extensions - Web APIs
also chrome doesn't plan to support any other extension in future extension identifier type description authnsel array of buffersource authenticator selection.
...if true, the client outputs an array of strings containing the extensions which are supported by the authenticator.
...if true, the client outputs an arraybuffer which contains a value uniquely identifying a user verification data record.
...And 2 more matches
PublicKeyCredentialCreationOptions - Web APIs
publickeycredentialcreationoptions.pubkeycredparams an array of element which specify the desired features of the credential, including its type and the algorithm used for the cryptographic signature operations.
... this array is sorted by descending order of preference.
... publickeycredentialcreationoptions.excludecredentials optional an array of descriptors for existing credentials.
...And 2 more matches
SubtleCrypto.digest() - Web APIs
data is an arraybuffer or arraybufferview containing the data to be digested.
... return value digest is a promise that fulfills with an arraybuffer containing the digest.
...he inhabitants refer to it as the planet earth.'; async function digestmessage(message) { const encoder = new textencoder(); const data = encoder.encode(message); const hash = await crypto.subtle.digest('sha-256', data); return hash; } const digestbuffer = await digestmessage(text); console.log(digestbuffer.bytelength); converting a digest to a hex string the digest is returned as an arraybuffer, but for comparison and display digests are often represented as hex strings.
...And 2 more matches
SubtleCrypto.encrypt() - Web APIs
return value result is a promise that fulfills with an arraybuffer containing the "ciphertext".
... function getmessageencoding() { const messagebox = document.queryselector(".aes-ctr #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } function encryptmessage(key) { let encoded = getmessageencoding(); // counter will be needed for decryption counter = window.crypto.getrandomvalues(new uint8array(16)); return window.crypto.subtle.encrypt( { name: "aes-ctr", counter, length: 64 }, key, encoded ); } let iv = new uint8array(16); let key = new uint8array(16); let data = new uint8array(12345); //crypto functions are wrapped in promises so we have to use await and make sure the function that //contains this code is an async function //encrypt function wan...
...ts a cryptokey object const key_encoded = await crypto.subtle.importkey( "raw", key.buffer, 'aes-ctr' , false, ["encrypt", "decrypt"]); const encrypted_content = await window.crypto.subtle.encrypt( { name: "aes-ctr", counter: iv, length: 128 }, key_encoded, data ); //uint8array console.log(encrypted_content); aes-cbc this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in cbc mode.
...And 2 more matches
Touch events - Web APIs
after that, we iterate over all the touch objects in the list, pushing them onto an array of active touchpoints and drawing the start point for the draw as a small circle; we're using a 4-pixel wide line, so a 4-pixel radius circle will show up neatly.
...ex, touches[i].pagey); ctx.linewidth = 4; ctx.strokestyle = color; ctx.stroke(); ongoingtouches.splice(idx, 1, copytouch(touches[i])); // swap in the new touch record console.log("."); } else { console.log("can't figure out which touch to continue"); } } } this iterates over the changed touches as well, but it looks in our cached touch information array for the previous information about each touch to determine the starting point for each touch's new line segment to be drawn.
... after drawing the line, we call array.splice() to replace the previous information about the touchpoint with the current information in the ongoingtouches array.
...And 2 more matches
WaveShaperNode.curve - Web APIs
the curve property of the waveshapernode interface is a float32array of numbers describing the distortion to apply.
... the mid-element of the array is applied to any signal value of 0, the first one to signal values of -1, and the last to signal values of 1; values lower than -1 or greater than 1 are treated like -1 or 1 respectively.
... note: the array can be a null value: in that case, no distortion is applied to the input signal.
...And 2 more matches
WebGL2RenderingContext.drawRangeElements() - Web APIs
the webgl2renderingcontext.drawrangeelements() method of the webgl api renders primitives from array data in a given range.
... start a gluint specifying the minimum array index contained in offset.
... end a gluint specifying the maximum array index contained in offset.
...And 2 more matches
WebGL2RenderingContext.texImage3D() - Web APIs
format, width, height, depth, border, format, type, htmlvideoelement source); void gl.teximage3d(target, level, internalformat, width, height, depth, border, format, type, imagebitmap source); void gl.teximage3d(target, level, internalformat, width, height, depth, border, format, type, imagedata source); void gl.teximage3d(target, level, internalformat, width, height, depth, border, format, type, arraybufferview?
... srcdata); void gl.teximage3d(target, level, internalformat, width, height, depth, border, format, type, arraybufferview srcdata, srcoffset); parameters target a glenum specifying the binding point (target) of the active texture.
... gl.texture_2d_array: a two-dimensional array texture.
...And 2 more matches
WebGL2RenderingContext.texSubImage3D() - Web APIs
syntax void gl.texsubimage3d(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, arraybufferview?
... gl.texture_2d_array: a two-dimensional array texture.
... gl.byte gl.unsigned_short gl.short gl.unsigned_int gl.int gl.half_float gl.float gl.unsigned_int_2_10_10_10_rev gl.unsigned_int_10f_11f_11f_rev gl.unsigned_int_5_9_9_9_rev gl.unsigned_int_24_8 gl.float_32_unsigned_int_24_8_rev (pixels must be null) pixels one of the following objects can be used as a pixel source for the texture: arraybufferview, a uint8array must be used if type is gl.unsigned_byte.
...And 2 more matches
WebGLRenderingContext.bufferSubData() - Web APIs
syntax // webgl1: void gl.buffersubdata(target, offset, arraybuffer srcdata); void gl.buffersubdata(target, offset, arraybufferview srcdata); // webgl2: void gl.buffersubdata(target, dstbyteoffset, arraybufferview srcdata, srcoffset, length); parameters target a glenum specifying the binding point (target).
... possible values: gl.array_buffer: buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data.
... gl.element_array_buffer: buffer used for element indices.
...And 2 more matches
WebGLRenderingContext.compressedTexImage[23]D() - Web APIs
syntax // webgl 1: void gl.compressedteximage2d(target, level, internalformat, width, height, border, arraybufferview?
... pixels); // additionally available in webgl 2: // read from buffer bound to gl.pixel_unpack_buffer void gl.compressedteximage2d(target, level, internalformat, width, height, border, glsizei imagesize, glintptr offset); void gl.compressedteximage2d(target, level, internalformat, width, height, border, arraybufferview srcdata, optional srcoffset, optional srclengthoverride); // read from buffer bound to gl.pixel_unpack_buffer void gl.compressedteximage3d(target, level, internalformat, width, height, depth, border, glsizei imagesize, glintptr offset); void gl.compressedteximage3d(target, level, internalformat, width, height, depth, border, arraybufferview srcdata, optional srcoffset, optional srclengthoverride); parameters target a...
... possible values for compressedteximage3d: gl.texture_2d_array gl.texture_3d level a glint specifying the level of detail.
...And 2 more matches
WebGLRenderingContext.getActiveUniform() - Web APIs
d gl.sampler_cube when using a webgl 2 context, the following values are possible additionally: gl.unsigned_int gl.unsigned_int_vec2 gl.unsigned_int_vec3 gl.unsigned_int_vec4 gl.float_mat2x3 gl.float_mat2x4 gl.float_mat3x2 gl.float_mat3x4 gl.float_mat4x2 gl.float_mat4x3 gl.sampler_2d gl.sampler_3d gl.sampler_cube gl.sampler_2d_shadow gl.sampler_2d_array gl.sampler_2d_array_shadow gl.sampler_cube_shadow gl.int_sampler_2d gl.int_sampler_3d gl.int_sampler_cube gl.int_sampler_2d_array gl.unsigned_int_sampler_2d gl.unsigned_int_sampler_3d gl.unsigned_int_sampler_cube gl.unsigned_int_sampler_2d_array when gl.linkprogram is called, webgl creates a list of active uniforms.
... array of basic type: one entry with the name of the uniform suffixed with [0].
... arrays of structs or arrays: each entry of the array will generate its own entries.
...And 2 more matches
WebGLRenderingContext.getUniformLocation() - Web APIs
uniform[1234][fi][v]() sets the uniform's value to the specified value, which may be a single floating point or integer number, or a 2-4 component vector specified either as a list of values or as a float32array or int32array.
...the value is represented as a sequence of glfloat values or as a float32array.
... additionally, for uniforms declared as arrays, the following names are also valid: the uniform name without the [0] suffix.
...And 2 more matches
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
for example, if the object is facing an object located at (3, 1, -2)—that is, three meters to the right, one meter up, and two meters away from the origin point—the result is: [31-2]\left [ \begin{matrix} 3 \\ 1 \\ -2 \end{matrix} \right ] this can also be represented as an array: let directionvector = [3, 1, -2]; for the purposes of performing operations involving both the coordinates and the facing direction vector, the vector needs to include the w component.
...property which is an xrrigidtransform providing the camera view, you can get the model view matrix—the transform matrix needed to move the world to simulate the desired camera position—like this: let viewmatrix = view.transform.inverse.matrix; if the library you're using accepts an xrrigidtransform object directly, you can instead get view.transform.inverse, rather than pulling out just the array representing the view matrix.
... the format for storing matrices is generally as a flat array in column-major order; that is, the values from the matrix are written starting with the top-left corner and moving down to the bottom, then moving over to the right a row and repeating until all values are in the array.
...And 2 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
next, we compile the shader programs; get references to its variables; initialize the buffers that store the array of each position; the indexes into the position table for each vertex; the vertex normals; and the texture coordinates for each vertex.
...x, normalmatrix); displaymatrix(view.projectionmatrix, 4, projectionmatrixout); displaymatrix(modelviewmatrix, 4, modelmatrixout); displaymatrix(view.transform.matrix, 4, cameramatrixout); displaymatrix(mousematrix, 4, mousematrixout); { const numcomponents = 3; const type = gl.float; const normalize = false; const stride = 0; const offset = 0; gl.bindbuffer(gl.array_buffer, buffers.position); gl.vertexattribpointer( programinfo.attriblocations.vertexposition, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexposition); } { const numcomponents = 2; const type = gl.float; const normalize = false; const stride = 0; ...
... const offset = 0; gl.bindbuffer(gl.array_buffer, buffers.texturecoord); gl.vertexattribpointer( programinfo.attriblocations.texturecoord, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.texturecoord); } { const numcomponents = 3; const type = gl.float; const normalize = false; const stride = 0; const offset = 0; gl.bindbuffer(gl.array_buffer, buffers.normal); gl.vertexattribpointer( programinfo.attriblocations.vertexnormal, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexnormal); } gl.bindbuffer(gl.element_array...
...And 2 more matches
Example and tutorial: Simple synth keyboard - Web APIs
let notefreq = null; let customwaveform = null; let sineterms = null; let cosineterms = null; finally, global variables that will be used when constructing waveforms are created: notefreq will be an array of arrays; each array represents one octave, each of which contains one entry for each note in that octave.
... sineterms and cosineterms will be used to store the data for generating the waveform; each will contain an array that's generated when the user chooses "custom".
... creating the note table the createnotetable() function builds the array notefreq to contain an array of objects representing each octave.
...And 2 more matches
Using XMLHttpRequest - Web APIs
for example, consider this snippet, which uses the responsetype of "arraybuffer" to fetch the remote content into a arraybuffer object, which stores the raw binary data.
... var oreq = new xmlhttprequest(); oreq.onload = function(e) { var arraybuffer = oreq.response; // not responsetext /* ...
... */ } oreq.open("get", url); oreq.responsetype = "arraybuffer"; oreq.send(); for more examples check out the sending and receiving binary data page monitoring progress xmlhttprequest provides the ability to listen to various events that can occur while the request is being processed.
...And 2 more matches
XMLHttpRequest.sendAsBinary() - Web APIs
polyfill since sendasbinary() is an experimental feature, here is a polyfill for browsers that don't support the sendasbinary() method but support typed arrays.
... /*\ |*| |*| :: xmlhttprequest.prototype.sendasbinary() polyfill :: |*| |*| https://developer.mozilla.org/docs/dom/xmlhttprequest#sendasbinary() |*| \*/ if (!xmlhttprequest.prototype.sendasbinary) { xmlhttprequest.prototype.sendasbinary = function (sdata) { var nbytes = sdata.length, ui8data = new uint8array(nbytes); for (var nidx = 0; nidx < nbytes; nidx++) { ui8data[nidx] = sdata.charcodeat(nidx) & 0xff; } /* send as arraybufferview...: */ this.send(ui8data); /* ...or as arraybuffer (legacy)...: this.send(ui8data.buffer); */ }; } note: it's possible to build this polyfill putting two types of data as argument for send(): an arraybuffer (ui8data.buffer – the commented code) or an arraybufferview (ui8data, which is a typed array of 8-bit unsigned integer...
...however, on google chrome, when you try to send an arraybuffer, the following warning message will appear: arraybuffer is deprecated in xmlhttprequest.send().
...And 2 more matches
XRViewerPose.views - Web APIs
the read-only xrviewerpose property views returns an array which contains every xrview which must be rendered in order to fully represent the scene from the viewpoint defined by the viewer pose.
... for monoscopic devices, this array contains a single view.
...for each frame, you should always use the current length of this array rather than caching the value.
...And 2 more matches
Iterators and generators - JavaScript
the most common iterator in javascript is the array iterator, which simply returns each value in the associated array in sequence.
... while it is easy to imagine that all iterators could be expressed as arrays, this is not true.
... arrays must be allocated in their entirety, but iterators are consumed only as necessary.
...And 2 more matches
TypeError: "x" is not a function - JavaScript
for example, javascript objects have no map function, but the javascript array object does.
...you will have to provide a function in order to have these methods working properly: when working with array or typedarray objects: array.prototype.every(), array.prototype.some(), array.prototype.foreach(), array.prototype.map(), array.prototype.filter(), array.prototype.reduce(), array.prototype.reduceright(), array.prototype.find() when working with map and set objects: map.prototype.foreach() and set.prototype.foreach() examples a typo in the function name in this case, which happens way too often, there is a typo in the method name: let x = document.getelementbyid('foo'); // typeerror: document.getelementbyid is not a function the correct function name is getelementbyid: let x = documen...
...in this example, array.prototype.map() is used, which will work with array objects only.
...And 2 more matches
Intl​.List​Format​.prototype​.formatToParts() - JavaScript
the intl.listformat.prototype.formattoparts() method returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.
... syntax intl.listformat.prototype.formattoparts(list) parameters list an array of values to be formatted according to a locale.
... return value an array of components which contains the formatted parts from the list.
...And 2 more matches
WeakMap - JavaScript
a map api could be implemented in javascript with two arrays (one for keys, one for values) shared by the four api methods.
... setting elements on this map would involve pushing a key and value onto the end of each of those arrays simultaneously.
... as a result, the indices of the key and value would correspond to both arrays.
...And 2 more matches
WebAssembly.validate() - JavaScript
the webassembly.validate() function validates a given typed array of webassembly binary code, returning whether the bytes form a valid wasm module (true) or not (false).
... syntax webassembly.validate(buffersource); parameters buffersource a typed array or arraybuffer containing webassembly binary code to be validated.
... exceptions if buffersource is not a typed array or arraybuffer, a typeerror is thrown.
...And 2 more matches
Trailing commas - JavaScript
javascript has allowed trailing commas in array literals since the beginning, and later added them to object literals (ecmascript 5) and most recently (ecmascript 2017) to function parameters.
... syntax , examples trailing commas in literals arrays javascript ignores trailing commas in arrays: var arr = [ 1, 2, 3, ]; arr; // [1, 2, 3] arr.length; // 3 if more than one trailing comma is used, an elision (or hole) is produced.
... an array with holes is called sparse (a dense array has no holes).
...And 2 more matches
window/utils - Archive of obsolete content
the exception is the windows() function which returns an array of currently opened windows.
... returns nsidomwindow windows() returns an array of all currently opened windows.
... returns array: array of nsidomwindow instances.
... parameters window : nsidomwindow returns array: array of frames.
package.json - Archive of obsolete content
contributors an array of additional author strings, identifying other contributors to the add-on.
... dependencies a string or an array of strings specifying the names of packages that this add-on requires in order to function properly.
... preferences an array of json objects that use the following keys: name,type, value, title, and description.
... translators an array of strings listing the people who contributed to the localization of this add-on.
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
opening binary files listing 13 shows how to get a files contents as a bytestring (where 1 byte = an array of 8 bits).
...p.txt'); var filestream = components.classes['@mozilla.org/network/file-input-stream;1'] .createinstance(components.interfaces.nsifileinputstream); filestream.init(file, 1, 0, false); var binarystream = components.classes['@mozilla.org/binaryinputstream;1'] .createinstance(components.interfaces.nsibinaryinputstream); binarystream.setinputstream(filestream); var array = binarystream.readbytearray(filestream.available()); binarystream.close(); filestream.close(); alert(array.map( function(aitem) {return aitem.tostring(16); } ).join(' ').touppercase( )); when we initialized nsifileinputstream, we set the second and third parameters to initialize it in read-only mode.
... listing 14: writing a binary file var array = [88, 85, 76]; file.initwithpath('c:\\temp\\temp.txt'); if (file.exists()) file.remove(true); file.create(file.normal_file_type, 0666); var filestream = components.classes['@mozilla.org/network/file-output-stream;1'] .createinstance(components.interfaces.nsifileoutputstream); filestream.init(file, 2, 0x200, false); var binarystream = components.classes['@mozilla.org/binaryoutp...
...utstream;1'] .createinstance(components.interfaces.nsibinaryoutputstream); binarystream.setoutputstream(filestream); binarystream.writebytearray(array , array.length); binarystream.close(); filestream.close(); text file i/o text files are read the same way streams are.
Creating a dynamic status bar extension - Archive of obsolete content
function inforeceived() { var samplepanel = document.getelementbyid('stockwatcher'); var output = httprequest.responsetext; if (output.length) { // remove whitespace from the end of the string; // this gets rid of the end-of-line characters output = output.replace(/\w*$/, ''); // build the tooltip string var fieldarray = output.split(','); // assert that fieldarray[0] == 'goog' samplepanel.label = 'goog: ' + fieldarray[1]; samplepanel.tooltiptext = 'chg: ' + fieldarray[4] + ' | ' + 'open: ' + fieldarray[5] + ' | ' + 'low: ' + fieldarray[6] + ' | ' + 'high: ' + fieldarray[7] + ' | ' + 'vol: ' + fieldarray[8]; } } the first thing we do here is get the status bar pane...
...we use the split() string function to split the comma-separated value string into its individual parts, with each field in a separate element in the array fieldarray.
...the status bar panel's label is set to indicate the current value of the stock, which is stored in fieldarray, by setting the samplepanel.label property.
...the string is built from a combination of static strings and various elements from the fieldarray array.
Dehydra Function Reference - Archive of obsolete content
decl is a variable type object representing the function being processed body is an array of {loc:, statements:array of variable types} representing an outline of the function stripped down to variables, function calls and assignments.
...this is accomplished by recording every included file into the _includedarray in the current namespace.
..."gnu c" or "gnu c++") arguments this.arguments is a javascript array containing command-line arguments passed to a script.
... -fplugin-arg="foo.js a b c" would run foo.js with ["a", "b", "c"] arguments array.
Space Manager Detailed Design - Archive of obsolete content
the 'count' member of the band data struct * indicates how large the array of trapezoids needs to be */ nsresult getbanddata(nscoord ayoffset, const nssize& amaxsize, nsbanddata& abanddata) const; /** * add a rectangular region of unavailable space.
... frameinfo(nsiframe* aframe, const nsrect& arect); #ifdef ns_build_refcnt_logging ~frameinfo(); #endif }; // doubly linked list of band rects struct bandrect : prcliststr { nscoord mleft, mtop; nscoord mright, mbottom; printn mnumframes; // number of frames occupying this rect union { nsiframe* mframe; // single frame occupying the space nsvoidarray* mframes; // list of frames occupying the space }; bandrect(nscoord aleft, nscoord atop, nscoord aright, nscoord abottom, nsiframe*); bandrect(nscoord aleft, nscoord atop, nscoord aright, nscoord abottom, nsvoidarray*); ~bandrect(); // list operations bandrect* next() const {return (bandrect*)pr_next_link(this);} b...
...the 'count' member of the band data struct * indicates how large the array of trapezoids needs to be */ nsresult getbanddata(nscoord ayoffset, const nssize& amaxsize, nsbanddata& abanddata) const; /** * add a rectangular region of unavailable space.
...the caller also provides a collection of banddata objects (an array) and the number of items that the collection can handle.
NPP_New - Archive of obsolete content
argc number of html arguments in the embed tag for an embedded plug-in; determines the number of attributes in the argn and argv arrays.
... argn[] array of attribute names passed to the plug-in from the embed tag.
... argv[] array of attribute values passed to the plug-in from the embed tag.
... all attributes in the embed tag (standard and private) are passed in npp_new in the argn and argv arrays.
E4X for templating - Archive of obsolete content
createbundle('chrome://myeext/locale/myext.properties'); if (args){ args = array.prototype.slice.call(arguments, 1); return strs.formatstringfromname(msg,args,args.length); } return strs.getstringfromname(msg); } for example, <toolbarbutton label={$s('mytoolbar.label')}/> conditionals function _if (cond, h, _else) { if (cond && cond != undefined) { // we need undefined condition for e4x return h(cond); } else if (_else) { return _...
...d at a later time, taking into account security considerations, such as escaping with the above), e4x content using such functions can also be easily serialized inline (and then perhaps converted to the dom) as needed: var list = <>{_if(elems.length(), function () <> <markup/> <markup/> </>)}</>.toxmlstring(); iterating functions such as the following foreach (which can work with arrays, objects, or e4x objects) are quite convenient in iterating over complex structures such as e4x would not normally allow.
...h more than one param (see below) ++it; } } else { for (k in arr) { if (it < min) { ++it; continue; } if (it > max) { break; } ret+=h(k, arr[k], it, lev); ++it; } } return ret; } the following real case example iterates over an array of the lines in an e4x child element to produce an xmllist of multiple vbox's representing each line: <vbox> {foreach(e(someel.somechild[0]).split('\n'), function (line) <description>{line}</description> )} </vbox> the following example shows iteration over an e4x object itself: {foreach(elems, function (k, elem, iter) <> <row>{k}: {elem}</row> <row><image src="chrome://myext/skin...
...item>banana</item> <item>grapes</item> </fruits>; alert( // using a javascript 1.8 expression closure <output> {sort(fruits.*, function (a, b) a.text() > b.text() /* text() call may not be necessary */ )} </output>.toxmlstring() ); /* <output> <item>banana</item> <item>grapes</item> <item>pear</item> </output> */ the above utility also works if the input is an htmlcollection, an array of strings, an array of dom objects, or an array of e4x objects (assuming the comparison function is changed or adapted accordingly).
Processing XML with E4X - Archive of obsolete content
continuing the above example, we can access an xmllist of the <lang> elements in the page as follows: var langs = languages.lang; xmllist provides a length() method which can be used to find the number of contained elements: alert(languages.lang.length()); note that unlike javascript arrays length is a method, not a property, and must be called using length().
... we can iterate through the matching elements like so: for (var i = 0; i < languages.lang.length(); i++) { alert(languages.lang[i].tostring()); } here we are using identical syntax to that used to access numbered items in an array.
... despite these similarities to regular arrays, xmllist does not support array methods such as foreach, and array generics such as array.foreach() are not compatible with xmllist objects.
...as with for...in, using it with arrays is strongly discouraged.
Archived JavaScript Reference - Archive of obsolete content
this property has been removed and no longer works.array comprehensionsthe array comprehension syntax was a javascript expression which allowed you to quickly assemble a new array based on an existing one.
...do not use it!array.observe()the array.observe() method was used for asynchronously observing changes to arrays, similar to object.observe() for objects.
...you can use the more general proxy object instead.array.unobserve()the array.unobserve() method was used to remove observers set by array.observe(), but has been deprecated and removed from browsers.
... you can use the more general proxy object instead.arraybuffer.transfer()the static arraybuffer.transfer() method returns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength.
JSObject - Archive of obsolete content
getslot retrieves the value of an array element of a javascript object.
... setslot sets the value of an array element of a javascript object.
...retrieves the value of an array element of a javascript object.
...sets the value of an array element of a javascript object.
Old Proxy API - Archive of obsolete content
object.getownpropertynames(proxy) getownpropertynames: function() -> strings array return an array of all own (non-inherited) property names of the emulated object.
... object.getpropertynames(proxy) getpropertynames: function() -> strings array this function doesn't exist in ecmascript 5.
... for(prop in proxy){...} enumerate: function() -> string array function() { return this.getpropertynames().filter( function (name) { return this.getpropertydescriptor(name).enumerable } ); } from the proxy user point of view, properties appear in the for..in loop in the same order as they are in the returned array.
... object.keys(proxy) keys: function() -> string array function() { return this.getownpropertynames().filter( function (name) { return this.getownpropertydescriptor(name).enumerable } ); } invariants even though proxies provide a lot of power to users, some operations are not trapped in order to keep the language consistent: the triple equal (===) operator is not trapped.
2D maze game with device orientation - Game development
to hold the block information we'll use a level data array: for each block we'll store the top and left absolute positions in pixels (x and y) and the type of the block — horizontal or vertical (t with the 'w' value meaning width and 'h' meaning height).
...]; every array element holds a collection of blocks with an x and y position and t value for each.
... after leveldata, but still in the initlevels function, we're adding the blocks into an array in the for loop using some of the framework-specific methods: for(var i=0; i<this.maxlevels; i++) { var newlevel = this.add.group(); newlevel.enablebody = true; newlevel.physicsbodytype = phaser.physics.arcade; for(var e=0; e<this.leveldata[i].length; e++) { var item = this.leveldata[i][e]; newlevel.create(item.x, item.y, 'element-'+item.t); } newlevel.setall('body.immovable', true); newlevel.visible = false; this.levels.push(newlevel); } first, add.group() is used to create a new group of items.
... the objects are stored in the this.levels array, which is by default invisible.
Manipulating documents - Learn web development
if you wanted to match and do things to multiple elements, you could use document.queryselectorall(), which matches every element in the document that matches the selector, and stores references to them in an array-like object called a nodelist.
... document.getelementsbytagname(), which returns an array-like object containing all the elements on the page of a given type, for example <p>s, <a>s, etc.
...const elementrefarray = document.getelementsbytagname('p').
... to start with, you can get a list of all the stylesheets attached to a document using document.stylesheets, which returns an array-like object with cssstylesheet objects.
Displaying Places information using views
void applyfilter( string filterstring, array folderrestrict ); parameters filterstring the new query's searchterms property will be set to this string.
... folderrestrict the setfolders function of the new query will be called on this array of folder ids.
... void load( array queries, nsinavhistoryqueryoptions options ); parameters queries an array of nsinavhistoryquery objects.
... void selectitems( array aids, array aopencontainers ); parameters aids an array of item ids.
How to implement a custom autocomplete search component
basic example for gecko 2.0 and up (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this example is your first best try because: it has no specific logic (it just returns a dummy array of choices) it doesn't care about compatibility with older gecko versions first copy the following javascript code into a file named basic_autocomplete.js into the components directory (or whatever components folder is appropriate in your case): warning: the uuid used below in chrome.manifest and assigned to class_id must be changed before use.
...ents.id('x753d830-ba1e-11e0-962b-0800200c9a66'); // ← change this const class_name = "basic autocomplete"; const contract_id = '@mozilla.org/autocomplete/search;1?name=basic-autocomplete'; /** * @constructor * * @implements {nsiautocompleteresult} * * @param {string} searchstring * @param {number} searchresult * @param {number} defaultindex * @param {string} errordescription * @param {array.<string>} results * @param {array.<string>|null=} comments */ function providerautocompleteresult(searchstring, searchresult, defaultindex, errordescription, results, comments) { this._searchstring = searchstring; this._searchresult = searchresult; this._defaultindex = defaultindex; this._errordescription = errordescription; this._results = results; this._comments = comments; } p...
...the json is converted into an array and used // as the source of match data.
... any values that match the search string // are moved into temporary arrays and passed to the autocompleteresult if (searchparam.length > 0) { var nativejson = components.classes["@mozilla.org/dom/json;1"].createinstance(ci.nsijson); var searchresults = nativejson.decode(searchparam); // these 2 lines above are for thunderbird < v7 // since thunderbird 3, they can be replaced more efficiently by the following line: // var searchresults = json.parse(searchparam); var results = []; var comments = []; for (i=0; i<searchresults.length; i++) { if (searchresults[i].value.indexof(searchstring) == 0) { results.push(searchresults[i].value); if (searchresults[i].comment) comments.push(searchresults[i].comment...
Addon
contributors read only addonauthor[] an array of strings holding the contributors of the add-on.
... developers read only addonauthor[] an array of strings holding the developers of the add-on.
... screenshots read only addonscreenshot[] an array of addonscreenshot objects containing urls of preview images for the add-on.
... translators read only addonauthor[] an array of strings holding the translators of the add-on.
DownloadList
method overview promise<array<download>> getall(); promise add(download adownload); promise remove(download adownload); promise addview(object aview); promise removeview(object aview); void removefinished([optional] function afilterfn); methods getall() retrieves a snapshot of the downloads that are currently in the list.
... the returned array does not change when downloads are added or removed, though the download objects it contains are still updated in real time.
... promise<array<download>> getall(); parameters none.
... promise resolves to an array of download objects.
Following the Android Toasts Tutorial from a JNI Perspective
the sig's will be represented as javascript strings in jni.jsm, and the sig's of the types are as follows: java type signature boolean z byte b char c class/object lclass name in slash notation here; double d float f int i long j short s void v array of type [sig here method format (sig of type of each argument here)sig of the return type here declaring a class/object is done in a special way.
...let's declare these methods in the third argument of loadclass we add a key-value pair, with the key being static_methods and methods and the value being an array.
... this is what our fields array will look like: static_fields: [ { name: 'length_short', sig: sig.int } ] wrap it all up here is the code for our completed toast class: var toast = jni.loadclass(my_jenv, sig.toast.substr(1, sig.toast.length - 2), { static_methods: [ { name: 'maketext', sig: '(' + sig.context + // context sig.int + // resid ...
...this is special: because a charsequence is an array of byte characters, we can pass simple javascript strings to jni.jsm wherever a charsequence is needed.
Examples
const {cu} = require("chrome"); const {textdecoder, textencoder, os} = cu.import("resource://gre/modules/osfile.jsm", {}); /* files: an array of file paths */ function readtextfiles(files) { let promises = [], decoder = new textdecoder(); for (let i = 0; i < files.length; i++) { let promise = os.file.read(files[i]) promise = promise.then(function onsuccess(array) { return decoder.decode(array); }); promises.push(promise); } return promise.all(promises); } let folder = "/path/to/folder"; let promise ...
...= readtextfiles([ os.path.join(folder, "read.me"), os.path.join(folder, "home.html") ]); promise.then( function onsuccess(filescontent) { // filescontent is an array of strings; each string is the content of one file.
...change the array in the code above.
... change this line: var imagepaths = ['http://www.mozilla.org/media/img/firefox/favicon.png', 'https://developer.cdn.mozilla.net/media/redesign/img/favicon32.png']; change it to: var imagepaths = ['http://www.mozilla.org/media/img/firefox/favicon.png', 'https://developer.cdn.mozilla.net/media/redesign/img/favicon32.png', 'blah blah']; i added 'blah blah' to that array, it will cuase the whole promise to reject.
sslfnc.html
ssl_implementedciphers[] is an external array of unsigned 16-bit integers whose values are either ssl2 cipher kinds or ssl3 cipher suites.
... warning: using the external array ssl_implementedciphers[] directly is deprecated.
... it causes dynamic linking issues at run-time after an update of nss because the actual size of the array changes between releases.
... the recommended way of accessing the array is through the ssl_getimplementedciphers() and ssl_getnumimplementedciphers() accessors.
Rhino FAQ
frequently asked questions about rhino how do i create a java array from javascript?
...for instance, to create an array of java.lang.string of length five, do var stringarray = java.lang.reflect.array.newinstance(java.lang.string, 5); then if you wish to assign the string "hi" to the first element, simply execute stringarray[0] = "hi".
... creating arrays of primitive types is slightly different: you must use the type field.
... for example, creating an array of seven ints can be done with the code var intarray = java.lang.reflect.array.newinstance(java.lang.integer.type, 7); when i try to execute a script i get the exception required security context missing.
Rhino overview
array.prototype.tostring and object.prototype.tostring version 1.2 only returns array or object literal notation ("[1]" or "{a:1, b:2}" for example).
... array constructor array(i) for a number argument i constructs an array with a single element equal to i for version 1.2 only.
... otherwise the ecma conformant version is used (an array is constructed with no elements but with length property equal to i).
...then, the class of the code that called to request the restricted action can be obtained by looking an appropriate index into the class context array.
Performance Hints
arrays use the forms of the array constructor that specify a size or take a list of initial elements.
... for example, the code var a = new array(); for (var i=0; i < n; i++) a[i] = i; could be sped up by changing the constructor call to new array(n).
... a constructor call like that indicates to the runtime that a javascript array should be used for the first n entries of the array.
... similarly, new array("a", "b", "c") or ["a", "b", "c"] will cause a 3-element array to be allocated to hold the contents of the javascript array.
SpiderMonkey Internals
so optimizations such as dense arrays and the property cache are, alas, not transparently tucked away in the jsarray.* and jsobj.* files.
... standard library the methods for arrays, booleans, dates, functions, numbers, and strings are implemented using the js api.
... var sumofdivisors = new exprarray(n + 1, 1); for (var divisor = 2; divisor <= n; divisor++) { for (var j = divisor + divisor; j <= n; j += divisor) { sumofdivisors[j] += " + " + divisor; } // at this point everything up to 'divisor' has its sumofdivisors // expression calculated, so we can determine whether it's perfect // already by evaluating.
... jsarray.*, jsbool.*, jsdate.*, jsfun.*, jsmath.*, jsnum.*, jsstr.* these file pairs implement the standard classes and (where they exist) their underlying primitive types.
JS_GetStringBytes
description js_getstringbytes and js_getstringbytesz convert the specified javascript string, str, to a c string (an array of 8-bit chars).
...on success, the return value is a pointer to the char array, which is null-terminated.
...the array returned by js_getstringbytes or js_getstringbytesz is automatically freed when str is finalized by the javascript garbage collection mechanism.
... the application must not modify the contents of the array.
JS_InitClass
ps jspropertyspec * either null or a pointer to the first element of an array of jspropertyspecs, terminated by the null jspropertyspec, which can be written {0, 0, 0, 0, 0}.
... fs jsfunctionspec * either null or a pointer to the first element of an array of jsfunctionspecs, terminated by js_fs_end.
...(this is the javascript equivalent of public, non-static methods in c++ or java.) static_ps jspropertyspec * either null or a pointer to the first element of an array of jspropertyspecs, terminated by the null jspropertyspec.
...(this is the nearest javascript equivalent of public static member variables in c++ or public static fields in java.) static_fs jsfunctionspec * either null or a pointer to the first element of an array of jsfunctionspecs, terminated by js_fs_end.
JS_NewStringCopyN
s const char* or const char16_t * pointer to the array of characters containing the text for the js string to create.
... description js_newstringcopyn allocates space for a javascript string and its underlying storage, and copies n characters from a c character array, s, into the new jsstring.
...the two functions differ only in the type of the character array s; both functions create ordinary javascript strings, and all javascript strings are made up of 16-bit characters.
... if the array s contains more than n characters, the new string contains a truncated version of the original string.
SpiderMonkey 1.8
this includes iterators and generators (bug 349263) and arrays (bug 417501).
... in short, applications that share objects among threads in such a way that two threads could access an array, iterator, or generator object at the same time should not use spidermonkey 1.8.
... new javascript language features javascript 1.8 adds array.reduce() and reduceright(), expression closures, and generator expressions.
... new macros js_fs, js_fn, and js_fs_end are recommended for populating jsfunctionspec arrays.
Using the Places tagging service
taggingsvc.taguri(uri("http://example.com/"), ["tag 1"]); //first argument = uri //second argument = array of tag(s) where uri() is probably similar to makeuri().
... tagginsvc.untaguri(uri("http://example.com/"), ["tag 1"]); //first argument = uri //second argument = array of tag(s) finding all urls with a given tag the nsitaggingservice.geturisfortag() method returns an array of all urls tagged with the given tag.
... var tag1uris = taggingsvc.geturisfortag("tag 1"); //"tag 1" = given tag getting all tags associated with a url the nsitaggingservice.gettagsforuri() method returns an array of all tags set for the given url.
... var tags = taggingsvc.gettagsforuri(uri("http://example.com/", {})); //tags = an array of tags stored in http://example.com/ see also places nsitaggingservice ...
XPCOM hashtable guide
hashtables may seem like arrays, but there are important differences: array hashtable keys: integer: arrays are always keyed on integers, and must be contiguous.
... lookup time: o(1): lookup time is a simple constant o(1): lookup time is mostly-constant, but the constant time can be larger than an array lookup sorting: sorted: stored sorted; iterated over in a sorted fashion.
... inserting/removing: o(n): adding and removing items from a large array can be time-consuming o(1): adding and removing items from hashtables is a quick operation wasted space: none: arrays are packed structures, so there is no wasted space.
... in these situations, an array, a linked-list, or various tree data structures are more efficient.
Detailed XPCOM hashtable guide
hashtables may seem like arrays, but there are important differences: array hashtable keys: integer: arrays are always keyed on integers, and must be contiguous.
... lookup time: o(1): lookup time is a simple constant o(1): lookup time is mostly-constant, but the constant time can be larger than an array lookup sorting: sorted: stored sorted; iterated over in a sorted fashion.
... inserting/removing: o(n): adding and removing items from a large array can be time-consuming o(1): adding and removing items from hashtables is a quick operation wasted space: none: arrays are packed structures, so there is no wasted space.
... in these situations, an array, a linked-list, or various tree data structures are more efficient.
XPCOM guide
MozillaTechXPCOMGuide
rnative for obtaining a service as compared to the indirect xpcom approach: getservice(), callgetservice(), etc methods are expensive and should be avoided when possible.receiving startup notificationssometimes it's necessary for xpcom components to receive notifications as to the progress of the application's startup process, so they can start new services at appropriate times, for example.xpcom array guidemozilla has many array classes because each array is optimized for a particular usage pattern.
... this guide describes the available arrays as well as the enumerator classes that can be used to get to them.
... in this document the term array refers to a container for multiple objects with a numeric, zero-based index.xpcom changes in gecko 2.0several changes that affect xpcom component compatibility are taking place in gecko 2.
...hashtables may seem like arrays, but there are important differences:xpcom stream guidein mozilla code, a stream is an object which represents access to a sequence of characters.
Components.utils.Sandbox
example of obtaining content principal from the window: var principal = gbrowser.selectedtab.linkedbrowser.contentprincipal; var sandbox = components.utils.sandbox(principal); expanded principal an expanded principal is specified as an array of the principals it subsumes.
... each item in the array should be an nsiprincipal, a dom window, or a uri.
... so this can be simply an array with a single element.
... wantglobalproperties an array of strings.
IAccessibleAction
keybinding() returns an array of bstrs describing one or more key bindings, if there are any, associated with the specified action.
...refer to @ref _arrayconsideration "special consideration when using arrays" for more details.
... keybindings an array of bstrs, allocated by the server, one for each key binding.
...nbindings the number of key bindings returned; the size of the returned array.
amIWebInstallListener
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) method overview boolean onwebinstallblocked(in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, [optional] in pruint32 acount); void onwebinstalldisabled(in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, [optional] in pruint32 acount); boolean onwebinstallrequested(in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, [optional] in pruint32 acount); ...
...boolean onwebinstallblocked( in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, in pruint32 acount optional ); parameters awindow the window that triggered the installs.
...void onwebinstalldisabled( in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, in pruint32 acount optional ); parameters awindow the window that triggered the installs.
...boolean onwebinstallrequested( in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, in pruint32 acount optional ); parameters awindow the window that triggered the installs.
mozISpellCheckingEngine
method overview void adddirectory(in nsifile dir); boolean check(in wstring word); void getdictionarylist([array, size_is(count)] out wstring dictionaries, out pruint32 count); void removedirectory(in nsifile dir); void suggest(in wstring word,[array, size_is(count)] out wstring suggestions, out pruint32 count); attributes attribute type description copyright wstring a string indicating the copyright of the engi...
...this will be either element from the array returned by getdictionarylist() or an empty string if no dictionary is selected.
...void getdictionarylist( [array, size_is(count)] out wstring dictionaries, out pruint32 count ); parameters dictionaries a list of dictionaries supported by this spell checker.
...void suggest( in wstring word, [array, size_is(count)] out wstring suggestions, out pruint32 count ); parameters word a word, which is misspelled according to check.
mozIStorageAggregateFunction
last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void onstep(in mozistoragevaluearray afunctionarguments); nsivariant onfinal(); methods onstep() this is called for each row of results returned by the query.
... void onstep( in mozistoragevaluearray afunctionarguments ); parameters afunctionarguments a mozistoragevaluearray holding the arguments passed in to the function.
...class standarddeviationfunc : public mozistorageaggregatefunction { public: ns_imethod onstep(mozistoragevaluearray *aarguments) { print32 value; nsresult rv = aarguments->getint32(&value); ns_ensure_success(rv, rv); mnumbers.appendelement(value); } ns_imethod onfinal(nsivariant **_result) { print64 total = 0; for (pruint32 i = 0; i < mnumbers.length(); i++) total += mnumbers[i]; print32 mean = total / mnumbers.length(); nstarray<print64> data(mnumbers); for...
...0; for (pruint32 i = 0; i < data.length(); i++) total += data[i]; nscomptr<nsiwritablevariant> result = do_createinstance("@mozilla.org/variant;1"); ns_ensure_true(result, ns_error_out_of_memory); rv = result->setasdouble(sqrt(double(total) / double(data.length()))); ns_ensure_success(rv, rv); ns_addref(*_result = result); return ns_ok; } private: nstarray<print32> mnumbers; }; // now, register our function with the database connection.
mozIStorageFunction
last changed in gecko 1.9.1.4 (firefox 3.5.4) inherits from: nsisupports method overview nsivariant onfunctioncall(in mozistoragevaluearray afunctionarguments); methods onfunctioncall() the implementation of the function.
... nsivariant onfunctioncall( in mozistoragevaluearray afunctionarguments ); parameters afunctionarguments a mozistoragevaluearray holding the arguments passed in to the function.
...class squarefunction : public mozistoragefunction { public: ns_imethod onfunctioncall(mozistoragevaluearray *aarguments, nsivariant **_result) { print32 value; nsresult rv = aarguments->getint32(&value); ns_ensure_success(rv, rv); nscomptr<nsiwritablevariant> result = do_createinstance("@mozilla.org/variant;1"); ns_ensure_true(result, ns_error_out_of_memory); rv = result->setasint64(value * value); ns_ensure_success(rv, rv); ns_addr...
... mozistoragevaluearray wraps an array of sql values, such as a result row.
nsIAccessibleRelation
method overview nsiaccessible gettarget(in unsigned long index); nsiarray gettargets(); attributes attribute type description relationtype unsigned long returns the type of the relation.
... gettargets() returns an array of accessible relation targets.
... nsiarray gettargets(); parameters none.
... return value an nsiarray object, each item in the array implements an nsiaccessible.
nsIAccessibleSelectable
inherits from: nsisupports last changed in gecko 1.7 method overview void addchildtoselection(in long index); void clearselection(); nsiarray getselectedchildren(); boolean ischildselected(in long index); nsiaccessible refselection(in long index); void removechildfromselection(in long index); boolean selectallselection(); attributes attribute type description selectioncount long the number of accessible children currently selected.
...getselectedchildren() returns an nsiarray of the selected nsiaccessible children.
... nsiarray getselectedchildren(); parameters none.
... return value an nsiarray.
nsIApplicationCache
method overview void activate(); void addnamespaces(in nsiarray namespaces); void discard(); void gatherentries(in pruint32 typebits, out unsigned long count, [array, size_is(count)] out string keys); nsiapplicationcachenamespace getmatchingnamespace(in acstring key); unsigned long gettypes(in acstring key); void initashandle(in acstring groupid, in acstring clientid); void markentry(in acstring key, in unsigned long typebits); void unmarkentry...
...void addnamespaces( in nsiarray namespaces ); parameters namespaces an nsiarray of nsiapplicationcachenamespace objects describing the namespaces to add to the cache.
...void gatherentries( in pruint32 typebits, out unsigned long count, [array, size_is(count)] out string keys ); parameters typebits a bit field indicating the types against which to match.
...keys an array of the keys matching one or more of the types indicated by typebits.
nsIClassInfo
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview nsisupports gethelperforlanguage(in pruint32 language); void getinterfaces(out pruint32 count, [array, size_is(count), retval] out nsiidptr array); attributes attribute type description classdescription string a human readable string naming the class, or null.
... if this method is not supported by an implementation, then it should return 0 for count and null for array.
... void getinterfaces( out pruint32 count, [array, size_is(count), retval] out nsiidptr array ); parameters count the length of the resulting array.
... array the resulting array of nsiidptr values.
nsIFaviconService
s service, use: var faviconservice = components.classes["@mozilla.org/browser/favicon-service;1"] .getservice(components.interfaces.nsifaviconservice); method overview void addfailedfavicon(in nsiuri afaviconuri); void expireallfavicons(); void getfavicondata(in nsiuri afaviconuri, out autf8string amimetype, [optional] out unsigned long adatalen, [array,retval,size_is(adatalen)] out octet adata); obsolete since gecko 22.0 astring getfavicondataasdataurl(in nsiuri afaviconuri); obsolete since gecko 22.0 nsiuri getfaviconforpage(in nsiuri apageuri); obsolete since gecko 22.0 nsiuri getfaviconimageforpage(in nsiuri apageuri); obsolete since gecko 22.0 nsiuri getfaviconlinkforicon(in nsiuri afaviconuri); ...
... boolean isfailedfavicon(in nsiuri afaviconuri); void removefailedfavicon(in nsiuri afaviconuri); void setandloadfaviconforpage(in nsiuri apageuri, in nsiuri afaviconuri, in boolean aforcereload, in unsigned long afaviconloadtype, [optional] in nsifavicondatacallback acallback); obsolete since gecko 22.0 void setfavicondata(in nsiuri afaviconuri, [const,array,size_is(adatalen)] in octet adata, in unsigned long adatalen, in autf8string amimetype, in prtime aexpiration); obsolete since gecko 22.0 void setfavicondatafromdataurl(in nsiuri afaviconuri, in astring adataurl, in prtime aexpiration); obsolete since gecko 22.0 void setfaviconurlforpage(in nsiuri apageuri, in nsiuri afaviconuri); obsolete since gecko 22.0 attributes attribute ...
...void getfavicondata( in nsiuri afaviconuri, out autf8string amimetype, out unsigned long adatalen, optional from gecko 2.0 [array,retval,size_is(adatalen)] out octet adata ); parameters afaviconuri uri of the favicon whose data is being read.
...void setfavicondata( in nsiuri afaviconuri, [const,array,size_is(adatalen)] in octet adata, in unsigned long adatalen, optional from gecko 2.0 in autf8string amimetype, in prtime aexpiration ); parameters afaviconuri uri of the favicon whose data is being set.
nsIMsgDBView
(in nsmsgviewindex index); nsimsgdbhdr getmsghdrat(in nsmsgviewindex index); nsimsgfolder getfolderforviewindex(in nsmsgviewindex index); acstring geturiforviewindex(in nsmsgviewindex index); nsimsgdbview clonedbview(in nsimessenger amessengerinstance, in nsimsgwindow amsgwindow, in nsimsgdbviewcommandupdater acommandupdater); void geturisforselection([array, size_is(count)] out string uris, out unsigned long count); void getindicesforselection([array, size_is(count)] out nsmsgviewindex indices, out unsigned long count); void loadmessagebymsgkey(in nsmsgkey amsgkey); void loadmessagebyviewindex(in nsmsgviewindex aindex); void loadmessagebyurl(in string aurl); void reloadmessage(); void reloadmessa...
... void geturisforselection([array, size_is(count)] out string uris, out unsigned long count); return values uris an array of urls for the selected messages.
... void getindicesforselection([array, size_is(count)] out nsmsgviewindex indices, out unsigned long count); return values indices the output array of indicies.
... each element of the array is an nsmsgviewindex which is defined as a unsigned long in mailnewstypes2.idl.
nsINavHistoryQueryResultNode
method overview void getqueries([optional] out unsigned long querycount, [retval,array,size_is(querycount)] out nsinavhistoryquery queries); attributes attribute type description folderitemid long long for both simple folder nodes and simple-folder-query nodes, this is set to the concrete itemid of the folder.
... void getqueries( out unsigned long querycount, optional from gecko 2.0 [retval,array,size_is(querycount)] out nsinavhistoryquery queries ); parameters querycount optional from gecko 2.0 the number of queries in the queries array.
... queries an array of nsinavhistoryquery objects describing the set of queries that build the node's children.
... there are querycount elements in the array.
nsIPrinterEnumerator
inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void displaypropertiesdlg(in wstring aprinter, in nsiprintsettings aprintsettings); void enumerateprinters(out pruint32 acount,[retval, array, size_is(acount)] out wstring aresult); obsolete since gecko 1.9 void initprintsettingsfromprinter(in wstring aprintername, in nsiprintsettings aprintsettings); attributes attribute type description defaultprintername wstring the name of the system default printer.
... methods displaypropertiesdlg() void displaypropertiesdlg( in wstring aprinter, in nsiprintsettings aprintsettings ); parameters aprinter aprintsettings enumerateprinters() obsolete since gecko 1.9 (firefox 3) returns an array of the names of all installed printers.
... void enumerateprinters( out pruint32 acount, [retval, array, size_is(acount)] out wstring aresult ); parameters acount returns number of printers returned.
... aresult returns array of names.
nsIProcess2
to create an instance, use: var process2 = components.classes["@mozilla.org/process/util;1"] .createinstance(components.interfaces.nsiprocess2); method overview void runasync([array, size_is(count)] in string args, in unsigned long count, [optional] in nsiobserver observer, [optional] in boolean holdweak); methods runasync() asynchronously runs the process with which the object was initialized, optionally calling an observer when the process finishes running.
... void runasync( [array, size_is(count)] in string args, in unsigned long count, in nsiobserver observer, optional in boolean holdweak optional ); parameters args an array of arguments to pass into the process, using the native character set.
... this array must have count entries.
... count the number of arguments passed in the args array.
nsIProfile
method overview void cloneprofile(in wstring profilename); void createnewprofile(in wstring profilename, in wstring nativeprofiledir, in wstring langcode, in boolean useexistingdir); void deleteprofile(in wstring name, in boolean candeletefiles); void getprofilelist(out unsigned long length, [retval, array, size_is(length)] out wstring profilenames); boolean profileexists(in wstring profilename); void renameprofile(in wstring oldname, in wstring newname); void shutdowncurrentprofile(in unsigned long shutdowntype); attributes attribute type description currentprofile wstring the name of the profile currently in use.
... getprofilelist() returns an array of strings indicating the names of all the available profiles.
... void getprofilelist( out unsigned long length, [retval, array, size_is(length)] out wstring profilenames ); parameters length on return, contains the number of profiles in the profilenames array.
... profilenames on return, contains an array of all of the available profiles' names.
nsIPromptService
ring atext, inout wstring ausername, inout wstring apassword, in wstring acheckmsg, inout boolean acheckstate); boolean promptpassword(in nsidomwindow aparent, in wstring adialogtitle, in wstring atext, inout wstring apassword, in wstring acheckmsg, inout boolean acheckstate); boolean select(in nsidomwindow aparent, in wstring adialogtitle, in wstring atext, in pruint32 acount, [array, size_is(acount)] in wstring aselectlist, out long aoutselection); constants the following flags are combined to form the abuttonflags parameter passed to confirmex.
...boolean select( in nsidomwindow aparent, in wstring adialogtitle, in wstring atext, in pruint32 acount, [array, size_is(acount)] in wstring aselectlist, out long aoutselection ); aparent the parent window for the dialog.
... acount length of the aselectlist array parameter.
...selected is the index of the item array // that was selected.
nsIPushMessage
method overview domstring text(); jsval json(); void binary([optional] out uint32_t datalen, [array, retval, size_is(datalen)] out uint8_t data); methods text() extracts the message data as a utf-8 text string.
... binary() extracts the message data as a byte array.
... void binary( [optional] out uint32_t datalen, [array, retval, size_is(datalen)] out uint8_t data ); parameters datalen the data size.
... data the byte array containing the data.
nsIPushSubscription
method overview void getkey(in domstring name, [optional] out uint32_t keylen, [array, size_is(keylen), retval] out uint8_t key); bool quotaapplies(); bool isexpired(); attributes attribute type description endpoint domstring the subscription url.
... methods getkey() returns a byte array containing the key material for this subscription.
... void getkey( in domstring name, [optional] out uint32_t keylen, [array, size_is(keylen), retval] out uint8_t key ); parameters name the encryption key name.
... key the byte array containing the keying material.
nsIScriptableUnicodeConverter
to create an instance, use: var converter = components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(components.interfaces.nsiscriptableunicodeconverter); method overview acstring convertfromunicode(in astring asrc); acstring finish(); astring converttounicode(in acstring asrc); astring convertfrombytearray([const,array,size_is(acount)] in octet adata, in unsigned long acount); void converttobytearray(in astring astring,[optional] out unsigned long alen,[array, size_is(alen),retval] out octet adata); nsiinputstream converttoinputstream(in astring astring); attributes attribute type description charset string current character set.
... astring converttounicode( in acstring asrc ); convertfrombytearray() converts an array of bytes to a unicode string.
... astring convertfrombytearray( [const,array,size_is(acount)] in octet adata, in unsigned long acount ); converttobytearray() convert a unicode string to an array of bytes.
... void converttobytearray(in astring astring, out unsigned long alen, optional [array, size_is(alen),retval] out octet adata ); converttoinputstream() converts a unicode string to an input stream.
nsISelection2
method overview void getrangesforinterval(in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, out pruint32 resultcount, [retval, array, size_is(resultcount)] out nsidomrange results); void getrangesforintervalcomarray(in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, in rangearray results); native code only!
... methods getrangesforinterval() return array of ranges intersecting with the given dom interval.
... void getrangesforinterval( in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, out pruint32 resultcount, [retval, array, size_is(resultcount)] out nsidomrange results ); parameters beginnode beginoffset endnode endoffset these four parameters represent the range to compare against the selection.
... native code only!getrangesforintervalcomarray void getrangesforintervalcomarray( in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool allowadjacent, in rangearray results ); parameters beginnode beginoffset endnode endoffset these four parameters represent the range to compare against the selection.
nsITelemetry
{ name1: {data1}, name2:{data2}...} where data consists of the following properties: min - minimal bucket size max - maximum bucket size histogram_type - histogram_exponential or histogram_linear counts - an array representing the values of buckets in the histogram.
... ranges - an array with corresponding bucket sizes.
... sum - sum of the counts array.
... keys() - returns an array with the string keys of the currently registered histograms.
nsIUpdateCheckListener
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void oncheckcomplete(in nsixmlhttprequest request, [array, size_is(updatecount)] in nsiupdate updates, in unsigned long updatecount); void onerror(in nsixmlhttprequest request, in nsiupdate update); void onprogress(in nsixmlhttprequest request, in unsigned long position, in unsigned long totalsize); methods oncheckcomplete() called when the update check is completed.
... void oncheckcomplete( in nsixmlhttprequest request, [array, size_is(updatecount)] in nsiupdate updates, in unsigned long updatecount ); parameters request the nsixmlhttprequest object handling the update check.
... updates an array of nsiupdate objects describing the available updates.
... updatecount the number of updates in the updates array.
nsIXmlRpcClient
constants constant type description int unsigned long nsisupportsprint32 boolean unsigned long nsisupportsprbool string unsigned long nsisupportscstring double unsigned long nsisupportsdouble datetime unsigned long nsisupportsprtime array readonly unsigned long nsisupportsarray struct readonly unsigned long nsisupportsdictionary methods init() set server url.
...supported arguments are: nsisupportspruint8, nsisupportspruint16, nsisupportsprint16, nsisupportsprint32: i4, nsisupportsprbool: boolean, nsisupportschar, nsisupportscstring: string, nsisupportsfloat, nsisupportsdouble: double, nsisupportsprtime: datetime.iso8601, nsiinputstream: base64, nsisupportsarray: array, nsidictionary: struct note that both nsisupportsarray and nsidictionary can only hold any of the supported input types.
... return value will be converted as follows: i4 or int: nsisupportsprint32 boolean: nsisupportsprbool string: nsisupportscstring double: nsisupportsdouble datetime.iso8601: nsisupportsprtime base64: nsisupportscstring array: nsisupportsarray struct: nsidictionary faults (server side errors) are indicated by returning ns_error_failure.
...parameters listener a nsixmlrpcclientlistener that will get notified of xml-rpc events ctxt a context to be passed on to the listener methodname remote method to call arguments array of arguments to pass to the remote method count void asynccall ( in nsixmlrpcclientlistener listener, in nsisupports ctxt, in string methodname, [array, size_is(count)] in nsisupports arguments, in pruint32 count ); createtype() convenience: return the correct nsisupportsprimitive for a given xml-rpc type, or nsisupportsarray or nsidictionary.
XPCOM Interface Reference
icontainerobserverimgidecoderimgidecoderobserverimgiencoderimgiloaderimgirequestinidomutilsjsdistackframemoziasyncfaviconsmoziasynchistorymozicoloranalyzermozijssubscriptloadermozipersonaldictionarymoziplaceinfomoziplacesautocompletemoziregistrymozirepresentativecolorcallbackmozispellcheckingenginemozistorageaggregatefunctionmozistorageasyncstatementmozistoragebindingparamsmozistoragebindingparamsarraymozistoragecompletioncallbackmozistorageconnectionmozistorageerrormozistoragefunctionmozistoragependingstatementmozistorageprogresshandlermozistorageresultsetmozistoragerowmozistorageservicemozistoragestatementmozistoragestatementcallbackmozistoragestatementparamsmozistoragestatementrowmozistoragestatementwrappermozistoragevacuumparticipantmozistoragevaluearraymozitxttohtmlconvmozithirdpartyutilmo...
...hangeeventnsiaccessibletextnsiaccessibletextchangeeventnsiaccessibletreecachensiaccessiblevaluensiaccessiblewin32objectnsialertsservicensiannotationobservernsiannotationservicensiappshellnsiappshellservicensiappstartupnsiappstartup_mozilla_2_0nsiapplicationcachensiapplicationcachechannelnsiapplicationcachecontainernsiapplicationcachenamespacensiapplicationcacheservicensiapplicationupdateservicensiarraynsiasyncinputstreamnsiasyncoutputstreamnsiasyncstreamcopiernsiasyncverifyredirectcallbacknsiauthinformationnsiauthmodulensiauthpromptnsiauthprompt2nsiauthpromptadapterfactorynsiauthpromptcallbacknsiauthpromptprovidernsiauthpromptwrappernsiautocompletecontrollernsiautocompleteinputnsiautocompleteitemnsiautocompletelistenernsiautocompleteobservernsiautocompleteresultnsiautocompletesearchnsibadcertli...
...sgdbviewnsimsgdbviewcommandupdaternsimsgdatabasensimsgfilternsimsgfiltercustomactionnsimsgfilterlistnsimsgfoldernsimsgheaderparsernsimsgidentitynsimsgincomingservernsimsgmessageservicensimsgprotocolinfonsimsgruleactionnsimsgsearchcustomtermnsimsgsearchnotifynsimsgsearchscopetermnsimsgsearchsessionnsimsgsearchtermnsimsgsearchvaluensimsgsendlaternsimsgthreadnsimsgwindownsimsgwindowcommandsnsimutablearraynsinavbookmarkobservernsinavbookmarksservicensinavhistorybatchcallbacknsinavhistorycontainerresultnodensinavhistoryfullvisitresultnodensinavhistoryobservernsinavhistoryquerynsinavhistoryqueryoptionsnsinavhistoryqueryresultnodensinavhistoryresultnsinavhistoryresultnodensinavhistoryresultobservernsinavhistoryresulttreeviewernsinavhistoryresultviewobservernsinavhistoryresultviewernsinavhistoryservice...
...atornsismsdatabaseservicensismsrequestmanagernsismsservicensisocketprovidernsisocketproviderservicensisockettransportnsisockettransportservicensisoundnsispeculativeconnectnsistackframensistandardurlnsistreamconverternsistreamlistenernsistringbundlensistringbundleoverridensistringbundleservicensistringenumeratornsistructuredclonecontainernsistylesheetservicensisupportsnsisupports proxiesnsisupportsarraynsisupportscstringnsisupportscharnsisupportsdoublensisupportsfloatnsisupportsidnsisupportsinterfacepointernsisupportsprboolnsisupportsprint16nsisupportsprint32nsisupportsprint64nsisupportsprtimensisupportspruint8nsisupportspruint16nsisupportspruint32nsisupportspruint64nsisupportsprimitivensisupportsprioritynsisupportsstringnsisupportsvoidnsisupportsweakreferencensisyncjpakensisyncmessagesendernsit...
Storage
let stmt = dbconn.createstatement("insert into table_name (value) values(:value)"); let params = stmt.newbindingparamsarray(); for (let i = 0; i < 10; i++) { let bp = params.newbindingparams(); bp.bindbyname("value", i); params.addparams(bp); } stmt.bindparameters(params); you can attach multiple sets of bindings to a statement by adding multiple mozistoragebindingparams objects to the array of parameter lists, adding each one through calls to the mozistoragebindingparamsarray.addparams().
...multiple statements can be executed in a transaction by calling mozistorageconnection.executeasync() on the connection and passing in an array of statements.
... in c++, the code would look something like this: bool hasmoredata; while (ns_succeeded(statement->executestep(&hasmoredata)) && hasmoredata) { print32 value; rv = statement->getint32(0, &value); ns_ensure_success(rv, rv); } you can obtain other types of data by using the various methods available on mozistoragevaluearray.
... mozistoragevaluearray wraps an array of sql values, such as a result row.
Mail composition back end
st struct nsmsgattachedfile *preloaded_attachments, - attachments that are already locally stored on disk (note: both attachments and preloaded_attachments cannot be specified on a single call void *relatedpart /* nsmsgsendpart */, - a related part for multipart related operations nsimsgsendlistener **alistenerarray) = 0; - an array of listeners for the send operation.
... nsimessage *msgtoreplace, - if the delivery mode is set to nsmsgsaveasdraft, this is a pointer to the the nsimessage object for the message that needs to be replaced nsimsgsendlistener **alistenerarray) = 0; - an array of listeners for the send operation.
...send later, drafts, templates or send the message now) nsimsgsendlistener **alistenerarray) = 0; - an array of listeners for the send operation.
... nsimsgsendlaterlistener **listenerarray) = 0; - an array of listeners for the send operation.
Adding items to the Folder Pane
this data is returned in the form of an array of folder-tree-items.
...this property is an array of folder-tree-items.
... each item in this array satisfies the following interface: id (attribute) a unique string for this object.
... must persist over sessions text (attribute) the text to display in the tree level (attribute) the level in the tree to display the item at open (rw, attribute) whether or not this container is open children (attribute) an array of child items also conforming to this spec getproperties (function) a call from getrowproperties or getcellproperties for this item will be passed into this function command (function) this function will be called when the item is double-clicked for our example extension, two different types of folder-tree-items will be defined.
DevTools API - Firefox Developer Tools
getdefaulttools() returns an array of tooldefinition objects for the built-in tools.
... getadditionaltools() returns an array of tooldefinition objects for tools added by addons.
... gettooldefinitionarray() returns an array of tooldefinition objects for enabled tools sorted by the order they appear in the toolbox.
... getthemedefinitionarray() returns an array of themedefinition objects for avialble themes.
Toolbox - Firefox Developer Tools
toolbox-hosted tools then there is an array of labeled buttons which enables you to switch between the different tools hosted by the toolbox.
... the array may include the following tools: web console javascript debugger page inspector style editor profiler network monitor note that not all the hosted tools are always listed here: only the tools actually available in this context are shown (for example, not all tools support remote debugging yet, so if the debugging target is not the firefox instance that launched the window, not all the hosted tools will be shown).
... extra tools next there's an array of buttons that can be added or removed in the developer tool settings.
... by default this array includes: toggle split console responsive design mode select a frame as the currently targeted document (this is only included by default from firefox 41 onwards).
Web Console Helpers - Firefox Developer Tools
$$(selector, element) looks up a css selector string selector, returning an array of dom nodes descended from element that match.
...this is like for document.queryselectorall(), but returns an array instead of a nodelist.
... $x(xpath, element, resulttype) evaluates the xpath xpath expression in the context of element and returns an array of matching nodes.
... pprint() obsolete since gecko 74 formats the specified value in a readable way; this is useful for dumping the contents of objects and arrays.
Web Console remoting - Firefox Developer Tools
to attach to the webconsoleactor, follow these steps: connecttoserver() // the usual listtabs() pickthetabyouwant() debuggerclient.attachconsole(tab.consoleactor, listeners, onattachconsole) the listeners argument is an array which specifies listeners you want to start in the web console.
...], "from": "conn0.console9" } each message in the array is of the same type as when we send typical page errors and console api calls.
...the prefs argument is an array of preferences you want to get their values for, by name.
...we change the arguments array - we create objectactor instances for each object passed as an argument - and, lastly, we remove some unneeded properties (like window ids).
AudioWorkletNodeOptions - Web APIs
outputchannelcount optional an array defining the number of channels for each output.
...the array length must match numberofoutputs.
...if the length of the outputchannelcount array doesn't match numberofoutputs, an indexsizeerror will be thrown.
...otherwise, the channel count of each channel in the set of output channels is set to match the corresponding value in the outputchannelcount array.
AuthenticatorAttestationResponse.getTransports() - Web APIs
gettransports() is a method of the authenticatorattestationresponse interface that returns an array containing strings describing the different transports which may be used by the authenticator.
... return value an array containing the different transports supported by the authenticator or nothing if this information is not available.of the processing of the different extensions by the client.
... the elements of this array are supposed to be in lexicographical order.
... examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var transports = newcredentialinfo.response.gettransports(); console.table(transports); // may be something like ["internal", "nfc", "usb"] }).catch(functio...
AuthenticatorAttestationResponse - Web APIs
authenticatorattestationresponse.attestationobject secure contextread only an arraybuffer containing authenticator data and an attestation statement for a newly-created key pair.
... methods authenticatorattestationresponse.gettransports()secure context returns an array of strings describing which transport methods (e.g.
...the array may be empty if the information is not available.
... examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var response = newcredentialinfo.response; // do something with the response // (sending it back to the relying party server maybe?) }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'authenticatorattestationresponse in...
AuthenticatorResponse.clientDataJSON - Web APIs
the clientdatajson property of the authenticatorresponse interface stores a json string in an arraybuffer, representing the client data that was passed to credentialscontainer.create() or credentialscontainer.get().
... syntax var arraybuffer = authenticatorattestationresponse.clientdatajson; var arraybuffer = authenticatorassertionresponse.clientdatajson; value an arraybuffer.
... properties after the clientdatajson object is converted from an arraybuffer to a javascript object, it will have the following properties: type a string which is either "webauthn.get" when an existing credential is retrieved or "webauthn.create" when a new credential is created.
... examples function arraybuffertostr(buf) { return string.fromcharcode.apply(null, new uint8array(buf)); } // pk is a publickeycredential that is the result of a create() or get() promise var clientdatastr = arraybuffertostr(pk.clientdatajson); var clientdataobj = json.parse(clientdatastr); console.log(clientdataobj.type); // "webauthn.create" or "webauthn.get" console.log(clientdataobj.challenge); // base64 en...
BaseAudioContext.createPeriodicWave() - Web APIs
parameters real an array of cosine terms (traditionally the a terms).
... imag an array of sine terms (traditionally the b terms).
... the real and imag arrays have to have the same length, otherwise an error is thrown.
... var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag, {disablenormalization: true}); osc.setperiodicwave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); this works because a sound that contains only a fundamental tone is by definition a s...
BluetoothRemoteGATTDescriptor - Web APIs
interface interface bluetoothremotegattdescriptor { readonly attribute bluetoothgattcharacteristic characteristic; readonly attribute uuid uuid; readonly attribute arraybuffer?
... value; promise<arraybuffer> readvalue(); promise<void> writevalue(buffersource value); }; properties bluetoothremotegattdescriptor.characteristicread only returns the bluetoothremotegattcharacteristic this descriptor belongs to.
... methods bluetoothremotegattdescriptor.readvalue() returns a promise that resolves to an arraybuffer holding a duplicate of the value property if it is available and supported.
... bluetoothremotegattdescriptor.writevalue() sets the value property to the bytes contained in an arraybuffer and returns a promise.
Cache.keys() - Web APIs
WebAPICachekeys
the keys() method of the cache interface returns a promise that resolves to an array of cache keys.
... syntax cache.keys(request, {options}).then(function(keys) { // do something with your array of requests }); parameters request optional the request want to return, if a specific key is desired.
... return value a promise that resolves to an array of cache keys.
... examples caches.open('v1').then(function(cache) { cache.keys().then(function(keys) { keys.foreach(function(request, index, array) { cache.delete(request); }); }); }) specifications specification status comment service workersthe definition of 'cache: keys' in that specification.
ContentIndex.getAll() - Web APIs
return value returns a promise that resolves with an array of contentdescription items.
... homepage article video audio icons: optional an array of image resources, defined as an object with the following data: src: a url string of the source image.
...if there are no items in the content index, an empty array is returned.
... async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const listelem = document.createelement('ul'); for (const entry of entri...
DOMMatrix - Web APIs
WebAPIDOMMatrix
fromfloat32array() creates a new mutable dommatrix object given an array of single-precision (32-bit) floating-point values.
... if the array has six values, the result is a 2d matrix; if the array has 16 values, the result is a 3d matrix.
... fromfloat64array() creates a new mutable dommatrix object given an array of double-precision (64-bit) floating-point values.
... if the array has six values, the result is a 2d matrix; if the array has 16 values, the result is a 3d matrix.
Introduction to the DOM - Web APIs
nodelist a nodelist is an array of elements, like the kind that is returned by the method document.getelementsbytagname().
...the latter uses the typical array syntax to fetch the second item in the list.
... namednodemap a namednodemap is like an array, but the items are accessed by name or index, though this latter case is merely a convenience for enumeration, as they are in no particular order in the list.
...it's common to refer to any attribute node as simply an attribute, for example, and to refer to an array of dom nodes as a nodelist.
Element.getElementsByClassName() - Web APIs
class of test, which are also a descendant of the element that has the id of main: document.getelementbyid('main').getelementsbyclassname('test'); matching multiple classes to find elements whose class lists include both the red and test classes: element.getelementsbyclassname('red test'); examining the results you can use either the item() method on the returned htmlcollection or standard array syntax to examine individual elements in the collection.
...s.item(i).classlist.add('hueframe'); } instead, use another method, such as: var matches = element.getelementsbyclassname('colorbox'); while (matches.length > 0) { matches.item(0).classlist.add('hueframe'); matches[0].classlist.remove('colorbox'); } this code finds descendant elements with the "colorbox" class, adds the class "hueframe", by calling item(0), then removes "colorbox" (using array notation).
... filtering the results using array methods we can also use methods of array.prototype on any htmlcollection by passing the htmlcollection as the method's this value.
... here we'll find all <div> elements that have a class of test: var testelements = document.getelementsbyclassname('test'); var testdivs = array.prototype.filter.call(testelements, function(testelement) { return testelement.nodename === 'div'; }); specifications specification status comment domthe definition of 'element.getelementsbyclassname()' in that specification.
Using Fetch - Web APIs
data.append('photos', photos.files[i]); } fetch('https://example.com/posts', { method: 'post', body: formdata, }) .then(response => response.json()) .then(result => { console.log('success:', result); }) .catch(error => { console.error('error:', error); }); processing a text file line by line the chunks that are read from a response are not broken neatly at line boundaries and are uint8arrays, not strings.
...a headers object is a simple multi-map of names to values: const content = 'hello world'; const myheaders = new headers(); myheaders.append('content-type', 'text/plain'); myheaders.append('content-length', content.length.tostring()); myheaders.append('x-custom-header', 'processthisimmediately'); the same can be achieved by passing an array of arrays or an object literal to the constructor: const myheaders = new headers({ 'content-type': 'text/plain', 'content-length': content.length.tostring(), 'x-custom-header': 'processthisimmediately' }); the contents can be queried and retrieved: console.log(myheaders.has('content-type')); // true console.log(myheaders.has('set-cookie')); // false myheaders.set('content-type', 'text/h...
...a body is an instance of any of the following types: arraybuffer arraybufferview (uint8array and friends) blob/file string urlsearchparams formdata the body mixin defines the following methods to extract a body (implemented by both request and response).
... arraybuffer() blob() json() text() formdata() this makes usage of non-textual data much easier than it was with xhr.
FileSystemDirectoryEntry.createReader() - Web APIs
example this example creates a method called readdirectory(), which fetches all of the entries in the specified filesystemdirectoryentry and returns them in an array.
... function readdirectory(directory) { let dirreader = directory.createreader(); let entries = []; let getentries = function() { dirreader.readentries(function(results) { if (results.length) { entries = entries.concat(toarray(results)); getentries(); } }, function(error) { /* handle error -- error is a fileerror object */ }); }; getentries(); return entries; } this works by creating an internal function, getentries(), which calls itself recursively to get all the entries in the directory, concatenating each batch to the array.
...when it returns an empty array, the end of the directory has beenr reached, and the recursion ends.
... once control is returned to readdirectory(), the array is returned to the caller.
Gamepad.buttons - Web APIs
WebAPIGamepadbuttons
the gamepad.buttons property of the gamepad interface returns an array of gamepadbutton objects representing the buttons present on the device.
... each entry in the array is 0 if the button is not pressed, and non-zero (typically 1.0) if the button is pressed.
... syntax readonly attribute gamepadbutton[] buttons; example the following code is taken from my gamepad api button demo (you can view the demo live, and find the source code on github.) note the code fork — in chrome navigator.getgamepads needs a webkit prefix and the button values are stores as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton objects; it is the gamepadbutton.value or gamepadbutton.pressed properties of these we need to access, depending on what type of buttons they are.
...ssed == true) { b--; } else if(gp.buttons[1].value > 0 || gp.buttons[1].pressed == true) { a++; } else if(gp.buttons[2].value > 0 || gp.buttons[2].pressed == true) { b++; } else if(gp.buttons[3].value > 0 || gp.buttons[3].pressed == true) { a--; } } ball.style.left = a*2 + "px"; ball.style.top = b*2 + "px"; var start = raf(gameloop); }; value an array of gamepadbutton objects.
Gamepad - Web APIs
WebAPIGamepad
a gamepad object can be returned in one of two ways: via the gamepad property of the gamepadconnected and gamepaddisconnected events, or by grabbing any position in the array returned by the navigator.getgamepads() method.
... properties gamepad.axes read only an array representing the controls with axes present on the device (e.g.
... gamepad.buttons read only an array of gamepadbutton objects representing the buttons present on the device.
... gamepad.hapticactuators read only an array containing gamepadhapticactuator objects, each of which represents haptic feedback hardware available on the controller.
Headers.getAll() - Web APIs
WebAPIHeadersgetAll
the getall() method of the headers interface used to return an array of all the values of a header within a headers object with a given name; in newer versions of the fetch spec, it has been deleted, and headers.get() has been updated to fetch all header values instead of only the first one.
... if the requested header doesn't exist in the headers object, it returns an empty array.
... returns an array containing a bytestring sequence representing the values of the retrieved header.
... example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then retrieve it using getall(): myheaders.append('content-type', 'image/jpeg'); myheaders.getall('content-type'); // returns [ "image/jpeg" ] if the header has multiple values associated with it, the array will contain all the values, in the order they were added to the headers object: myheaders.append('accept-encoding', 'deflate'); myheaders.append('accept-encoding', 'gzip'); myheaders.getall('accept-encoding'); // returns [ "deflate", "gzip" ] note: use headers.get to return only the first value added to the headers object.
PaymentRequest.PaymentRequest() - Web APIs
syntax var paymentrequest = new paymentrequest(methoddata, details, [options]); parameters methoddata contains an array of identifiers for the payment methods the merchant web site accepts and any associated payment method specific data.
... each item in the array contains the following fields: supportedmethods for early implementations of the spec, this was a sequence of identifiers for payment methods that the merchant website accepts.
... displayitems an array of optional line items for the payment request that the user agent may display, such as product details, tax, and shipping.
...this parameter contains the following fields: additionaldisplayitems an array of items to be appended to the details.displayitems property.
PublicKeyCredential.getClientExtensionResults() - Web APIs
getclientextensionresults() is a method of the publickeycredential interface that returns an arraybuffer which contains a map between the extensions identifiers and their results after having being processed by the client.
... syntax maparraybuffer = publickeycredential.getclientextensionresults() parameters none.
... return value an arraybuffer containing the result of the processing of the different extensions by the client.
... examples var publickey = { // here are the extensions (as "inputs") extensions: { "loc": true, // this extension has been defined to include location information in attestation "uvi": true // user verification index: how the user was verified }, challenge: new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var mybuffe...
PublicKeyCredentialCreationOptions.excludeCredentials - Web APIs
excludecredentials, an optional property of the publickeycredentialcreationoptions dictionary, is an array whose elements are descriptors for the public keys already existing for a given user.
... syntax excludecredentials = publickeycredentialcreationoptions.excludecredentials value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created.
... transports optional an array of strings describing the possible transports between the client and the authenticator.
... examples var publickey = { excludecredentials: [ { type: "public-key", // the id for john.doe@example.com id : new uint8array(26) /* this actually is given by the server */ }, { type: "public-key", // the id for john-doe@example.com id : new uint8array(26) /* another id */ } ], challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each use...
PublicKeyCredentialCreationOptions.pubKeyCredParams - Web APIs
the pubkeycredparams property of the publickeycredentialcreationoptions dictionary is an array whose elements are objects describing the desired features of the credential to be created.
... if this array contains multiple elements, they are sorted by descending order of preference.
... syntax pubkeycredparams = publickeycredentialcreationoptions.pubkeycredparams value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created.
... examples var publickey = { pubkeycredparams: [ // we would like an elliptic curve to be used if possible { type: "public-key", alg: -7 }, // if not, then we will fallback on an rsa algorithm { type: "public-key", alg: -37 } ], challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", } }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions ...
PublicKeyCredentialRequestOptions.allowCredentials - Web APIs
this is an array of credential descriptors.
... syntax allowcredentials = publickeycredentialrequestoptions.allowcredentials value an array whose elements are objects with the following properties: type a string describing type of public-key credential to be created.
... transports optional an array of strings describing the possible transports between the client and the authenticator.
... examples var options = { allowcredentials: [ { transports: ["usb"], type: "public-key", id: new uint8array(26) // actually provided by the server }, { transports: ["internal"], type: "public-key", id: new uint8array(26) // actually provided by the server } ], challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the serv...
PublicKeyCredentialRequestOptions.extensions - Web APIs
txauthgeneric an object with two properties: contenttype (usvstring) content (arraybuffer) generic transaction authorization.
...if true, the client outputs an arraybuffer which contains a value uniquely identifying a user verification data record.
...if true, the client outputs an array of arrays with 3 values containing information about how the user was verified (e.g.
... examples var options = { extensions: { uvm: true, loc: false, txauthsimple: "could you please verify yourself?" }, challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api...
RTCConfiguration.iceServers - Web APIs
the rtcconfiguration dictionary's iceservers property is an array of rtciceserver objects, each of which describes a single stun or turn server to use for negotiation purposes.
...]; value an array of zero or more rtciceserver objects, each of which describes one stun or turn server for the ice agent to use during the connection's negotiation.
... each object must at least have an urls property, which is an array of one or more strings, each providing one server's url.
... if the array is empty, or if the iceservers option isn't specified, the ice agent will negotiate without the use of any servers, which will limit the connection to local peers.
RTCDataChannel.binaryType - Web APIs
values allowed by the websocket.binarytype property are also permitted here: "blob" if blob objects are being used or "arraybuffer" if arraybuffer objects are being used.
... "arraybuffer" received binary messages' contents will be contained in arraybuffer objects.
... example this code configures a data channel to receive binary data in arraybuffer objects, and establishes a listener for message events which constructs a string representing the received data as a list of hexadecimal byte values.
... var dc = peerconnection.createdatachannel("binary"); dc.binarytype = "arraybuffer"; dc.onmessage = function(event) { let bytearray = new uint8array(event.data); let hexstring = ""; bytearray.foreach(function(byte) { hexstring += byte.tostring(16) + " "; }); }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.binarytype' in that specification.
ReadableStream.tee() - Web APIs
the tee() method of the readablestream interface tees the current readable stream, returning a two-element array containing the two resulting branches as new readablestream instances.
... return value an array containing two readablestream instances.
... examples in the following simple example, a previously-created stream is teed, then both resulting streams (contained in two members of a generated array) are passed to a function that reads the data out of the two streams and prints each stream's chunks sequentially to a different part of the ui.
... if (done) { console.log("stream complete"); return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'read ' + charsreceived + ' characters so far.
ResizeObserverEntry.borderBoxSize - Web APIs
the borderboxsize read-only property of the resizeobserverentry interface returns an array containing the new border box size of the observed element when the callback is run.
... syntax var myborderboxsize = resizeobserverentry.borderboxsize; value an array containing objects with the new border box size of the observed element.
... the array is necessary to support elements that have multiple fragments, which occur in multi-column scenarios.
... each object in the array contains two properties: blocksize the length of the observed element's border box in the block dimension.
SpeechRecognitionResultList - Web APIs
properties speechrecognitionresultlist.length read only returns the length of the "array" — the number of speechrecognitionresult objects in the list.
... methods speechrecognitionresultlist.item a standard getter that allows speechrecognitionresult objects in the list to be accessed via array syntax.
... // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
StylePropertyMapReadOnly - Web APIs
methods stylepropertymapreadonly.entries() returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
... stylepropertymapreadonly.getall() returns an array of cssstylevalue objects containing the values for the provided property.
... stylepropertymapreadonly.keys() returns a new array iterator containing the keys for each item in stylepropertymapreadonly.
... stylepropertymapreadonly.values() returns a new array iterator containing the values for each index in the stylepropertymapreadonly object.
WebGL2RenderingContext.drawElementsInstanced() - Web APIs
the webgl2renderingcontext.drawelementsinstanced() method of the webgl 2 api renders primitives from array data like the gl.drawelements() method.
... note: when using webgl 1, the angle_instanced_arrays extension can provide this method, too.
... type a glenum specifying the type of the values in the element array buffer.
... possible values are: gl.unsigned_byte gl.unsigned_short when using the oes_element_index_uint extension: gl.unsigned_int offset a glintptr specifying an offset in the element array buffer.
WebGLRenderingContext.bindBuffer() - Web APIs
possible values: gl.array_buffer: buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data.
... gl.element_array_buffer: buffer used for element indices.
... examples binding a buffer to a target var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); getting current bindings to check the current buffer bindings, query the array_buffer_binding and element_array_buffer_binding constants.
... gl.getparameter(gl.array_buffer_binding); gl.getparameter(gl.element_array_buffer_binding); specifications specification status comment webgl 1.0the definition of 'bindbuffer' in that specification.
WebGLRenderingContext.vertexAttrib[1234]f[v]() - Web APIs
value a float32array for floating point vector vertex attribute values.
... this value will be used if a bound array buffer has not been enabled with enablevertexattribarray.
...they aren't part of the shader state (like generix vertex attribute indexes to shader variable bindings) and aren't part of the vertex array object state (like enabled vertex attribute arrays).
... examples const a_foobar = gl.getattriblocation(shaderprogram, 'foobar'); //either set each component individually: gl.vertexattrib3f(a_foobar, 10.0, 5.0, 2.0); //or provide a float32array: const floatarray = new float32array([10.0, 5.0, 2.0]); gl.vertexattrib3fv(a_foobar, floatarray); // we want to load the following 3x3 matrix into attribute named "matrix3x3" // 0 1 2 // 3 4 5 // 6 7 8 const matrix3x3location = gl.getattriblocation(shaderprogram, 'matrix3x3'); gl.vertexattrib3f(matrix3x3location, 0, 3, 6); gl.vertexattrib3f(matrix3x3location + 1, 1, 4, 7); gl.vertexattrib3f(matrix3x3location + 2, 2, 5, 8); specifications specification status comment webgl 1.0the definition of 'vertexattrib...
Using shaders to apply color in WebGL - Web APIs
to do this, we first need to create an array of vertex colors, then store it into a webgl buffer.
... const colors = [ 1.0, 1.0, 1.0, 1.0, // white 1.0, 0.0, 0.0, 1.0, // red 0.0, 1.0, 0.0, 1.0, // green 0.0, 0.0, 1.0, 1.0, // blue ]; const colorbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, colorbuffer); gl.bufferdata(gl.array_buffer, new float32array(colors), gl.static_draw); return { position: positionbuffer, color: colorbuffer, }; } this code starts by creating a javascript array containing four 4-value vectors, one for each vertex color.
... then a new webgl buffer is allocated to store these colors, and the array is converted into floats and stored into the buffer.
... { const numcomponents = 4; const type = gl.float; const normalize = false; const stride = 0; const offset = 0; gl.bindbuffer(gl.array_buffer, buffers.color); gl.vertexattribpointer( programinfo.attriblocations.vertexcolor, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexcolor); } view the complete code | open this demo on a new page « previousnext » ...
Using bounded reference spaces - Web APIs
the boundary is then defined using an array of 2d coordinates, specifying only the x and z components since y is always 0.
... understanding boundaries as mentioned previously, the boundary is defined as an array of points located at floor level, each defining a corner of the boundary area, going around the origin in a clockwise manner.
...this property contains an array of dompointreadonly objects, each of which defines one of the points making up the space's border, moving around the room in clockwise order.
... each vertex in the array has a y coordinate of 0 since the entire boundary is defined at floor level, extending upward to the ceiling or indefinitely.
Keyframe Formats - Web APIs
syntax there are two different ways to format keyframes: an array of objects (keyframes) consisting of properties and values to iterate over.
... an object containing key-value pairs consisting of the property to animate and an array of values to iterate over.
... element.animate({ opacity: [ 0, 1 ], // [ from, to ] color: [ "#fff", "#000" ] // [ from, to ] }, 2000); using this format, the number of elements in each array does not need to be equal.
...if there are insufficient values, or if the list contains null values, the keyframes without specified offsets will be evenly spaced as with the array format described above.
Basic concepts behind Web Audio API - Web APIs
you can grab data using the following methods: analysernode.getfloatfrequencydata() copies the current frequency data into a float32array array passed into it.
... analysernode.getbytefrequencydata() copies the current frequency data into a uint8array (unsigned byte array) passed into it.
... analysernode.getfloattimedomaindata() copies the current waveform, or time-domain, data into a float32array array passed into it.
... analysernode.getbytetimedomaindata() copies the current waveform, or time-domain, data into a uint8array (unsigned byte array) passed into it.
XRBoundedReferenceSpace.boundsGeometry - Web APIs
the read-only xrboundedreferencespace property boundsgeometry is an array of dompointreadonly objects which specifies the points making up a polygon inside which the viewer is allowed to move.
... syntax bounds = xrreferencespace.boundsgeometry; value the boundsgeometry property is an array of dompointreadonly objects, each of which defines one vertex in a polygon inside which the viewer is required to remain.
...additionally, the value of w is always 1 in every point in the array.
... in order to reduce the risk of the room boundaries being used for fingerprinting purposes, each point in the boundsgeometry array may be rounded or adjusted by some amount.
XRRigidTransform.matrix - Web APIs
syntax let matrix = xrrigidtransform.matrix; value a float32array containing 16 entries which represents the 4x4 transform matrix which is described by the position and orientation properties.
... usage notes matrix format all 4x4 transform matrices used in webgl are stored in 16-element float32arrays.
... the values are stored into the array in column-major order; that is, each column is written into the array top-down before moving to the right one column and writing the next column into the array.
... thus, for an array [a0, a1, a2, ..., a13, a14, a15], the matrix looks like this: [a[0]a[4]a[8]a[12]a[1]a[5]a[9]a[13]a[2]a[6]a[10]a[14]a[3]a[7]a[11]a[15]]\begin{bmatrix} a[0] & a[4] & a[8] & a[12]\\ a[1] & a[5] & a[9] & a[13]\\ a[2] & a[6] & a[10] & a[14]\\ a[3] & a[7] & a[11] & a[15]\\ \end{bmatrix} the first time matrix is requested, it gets computed; after that, it's should be cached to avoid slowing down to compute it every time you need it.
ARIA: grid role - Accessibility
00; } tbody td[role="gridcell"]:hover, tbody td[role="gridcell"]:focus { background-color: #f6f6f6; outline: 3px solid blue; } } javascript var selectables = document.queryselectorall('table td[role="gridcell"]'); selectables[0].setattribute('tabindex', 0); var trs = document.queryselectorall('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; array.prototype.foreach.call(trs, function(gridrow, i){ array.prototype.foreach.call(gridrow.queryselectorall('td'), function(el, i){ el.dataset.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(newrow, newcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol ...
...+ '"]'); if (tgt && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); return true; } else { return false; } } document.queryselector('table').addeventlistener("keydown", function(event) { switch (event.key) { case "arrowright": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) + 1); break; case "arrowleft": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) - 1); break; case "arrowdown": moveto(parseint(event.target.dataset.row, 10) + 1, parseint(event.target.dataset.col, 10)...
...color: #000; } tbody td[role="gridcell"]:hover, tbody td[role="gridcell"]:focus { background-color: #f6f6f6; outline: 3px solid blue; } javascript var selectables = document.queryselectorall('table td[role="gridcell"]'); selectables[0].setattribute('tabindex', 0); var trs = document.queryselectorall('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; array.prototype.foreach.call(trs, function(gridrow, i){ array.prototype.foreach.call(gridrow.queryselectorall('td'), function(el, i){ el.dataset.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(newrow, newcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol ...
...+ '"]'); if (tgt && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); return true; } else { return false; } } document.queryselector('table').addeventlistener("keydown", function(event) { switch (event.key) { case "arrowright": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) + 1); break; case "arrowleft": moveto(parseint(event.target.dataset.row, 10), parseint(event.target.dataset.col, 10) - 1); break; case "arrowdown": moveto(parseint(event.target.dataset.row, 10) + 1, parseint(event.target.dataset.col, 10)...
Getting Started - Developer guides
"!"; $array = ['username' => $name, 'computedstring' => $computedstring]; echo json_encode($array); for more on dom methods, be sure to check out document object model (dom).
... simple timed xhr example another simple example follows — here we are loading a text file via xhr, the structure of which is assumed to be like this: time: 312.05 time: 312.07 time: 312.10 time: 312.12 time: 312.14 time: 312.15 once the text file is loaded, we split() the items into an array at each newline character (\n — basically where each line break is in the text file), and then print the complete list of timestamps, and the last timestamp, onto the page.
... const lastdata = document.getelementbyid('laststamp'); function fetchdata() { console.log('fetching updated data.'); let xhr = new xmlhttprequest(); xhr.open("get", "time-log.txt", true); xhr.onload = function() { updatedisplay(xhr.response); } xhr.send(); } function updatedisplay(text) { fulldata.textcontent = text; let timearray = text.split('\n'); // included because some file systems always include a blank line at the end of text files.
... if(timearray[timearray.length-1] === '') { timearray.pop(); } lastdata.textcontent = timearray[timearray.length-1]; } setinterval(fetchdata, 5000); </script> </body> </html> ...
Loops and iteration - JavaScript
example 1 the following example iterates through the elements in an array until it finds the index of an element whose value is thevalue: for (let i = 0; i < a.length; i++) { if (a[i] === thevalue) { break; } } example 2: breaking to a label let x = 0; let z = 0; labelcancelloops: while (true) { console.log('outer loops: ' + x); x += 1; z = 1; while (true) { console.log('inner loops: ' + z); z += 1; if (z === 10 && x === 10) { break...
... function dump_props(obj, obj_name) { let result = ''; for (let i in obj) { result += obj_name + '.' + i + ' = ' + obj[i] + '<br>'; } result += '<hr>'; return result; } for an object car with properties make and model, result would be: car.make = ford car.model = mustang arrays although it may be tempting to use this as a way to iterate over array elements, the for...in statement will return the name of your user-defined properties in addition to the numeric indexes.
... therefore, it is better to use a traditional for loop with a numeric index when iterating over arrays, because the for...in statement iterates over user-defined properties in addition to the array elements, if you modify the array object (such as adding custom properties or methods).
... for...of statement the for...of statement creates a loop iterating over iterable objects (including array, map, set, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
Deprecated and obsolete features - JavaScript
js1.7/js1.8 array comprehension and js1.7/js1.8 generator comprehension are deprecated.
... array property description array.observe() asynchronously observing changes to arrays.
... array.unobserve() remove observers.
... number number.tointeger() parallelarray parallelarray statements for each...in is deprecated.
TypeError: 'x' is not iterable - JavaScript
the javascript exception "is not iterable" occurs when the value which is given as the right hand-side of for…of or as argument of a function such as promise.all or typedarray.from, is not an iterable object.
... the value which is given as the right hand-side of for…of or as argument of a function such as promise.all or typedarray.from, is not an iterable object.
... an iterable can be a built-in iterable type such as array, string or map, a generator result, or an object implementing the iterable protocol.
... } } array.from(myemptyiterable); // typeerror: myemptyiterable is not iterable here is a correct implementation: const myemptyiterable = { [symbol.iterator]() { return [][symbol.iterator]() } } array.from(myemptyiterable); // [] ...
DataView() constructor - JavaScript
syntax new dataview(buffer [, byteoffset [, bytelength]]) parameters buffer an existing arraybuffer or sharedarraybuffer to use as the storage backing the new dataview object.
... bytelength optional the number of elements in the byte array.
...(that probably wasn't a very helpful description.) you can think of the returned object as an "interpreter" of the array buffer of bytes — it knows how to convert numbers to fit within the buffer correctly, both when reading and writing to it.
... examples using dataview var buffer = new arraybuffer(16); var view = new dataview(buffer, 0); view.setint16(1, 42); view.getint16(1); // 42 specifications specification ecmascript (ecma-262)the definition of 'dataview constructor' in that specification.
Intl.Collator.supportedLocalesOf() - JavaScript
the intl.collator.supportedlocalesof() method returns an array containing those of the provided locales that are supported in collation without having to fall back to the runtime's default locale.
... syntax intl.collator.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings.
... return value an array of strings representing a subset of the given locale tags that are supported in collation without having to fall back to the runtime's default locale.
... description returns an array with a subset of the language tags provided in locales.
Intl.DateTimeFormat.supportedLocalesOf() - JavaScript
the intl.datetimeformat.supportedlocalesof() method returns an array containing those of the provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale.
... syntax intl.datetimeformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings.
... return value an array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale.
... description returns an array with a subset of the language tags provided in locales.
Intl.DisplayNames.supportedLocalesOf() - JavaScript
the intl.displaynames.supportedlocalesof() method returns an array containing those of the provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale.
... syntax intl.displaynames.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings.
... return value an array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale.
... description returns an array with a subset of the language tags provided in locales.
Intl.ListFormat.supportedLocalesOf() - JavaScript
the intl.listformat.supportedlocalesof() method returns an array containing those of the provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale.
... syntax intl.listformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings.
... return value an array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale.
... description returns an array with a subset of the language tags provided in locales.
Intl.NumberFormat.supportedLocalesOf() - JavaScript
the intl.numberformat.supportedlocalesof() method returns an array containing those of the provided locales that are supported in number formatting without having to fall back to the runtime's default locale.
... syntax intl.numberformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings.
... return value an array of strings representing a subset of the given locale tags that are supported in number formatting without having to fall back to the runtime's default locale.
... description returns an array with a subset of the language tags provided in locales.
Intl.PluralRules.supportedLocalesOf() - JavaScript
the intl.pluralrules.supportedlocalesof() method returns an array containing those of the provided locales that are supported in plural formatting without having to fall back to the runtime's default locale.
... syntax intl.pluralrules.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings.
... return value an array of strings representing a subset of the given locale tags that are supported in plural formatting without having to fall back to the runtime's default locale.
... description returns an array with a subset of the language tags provided in locales.
Intl.RelativeTimeFormat.supportedLocalesOf() - JavaScript
the intl.relativetimeformat.supportedlocalesof() method returns an array containing those of the provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale.
... syntax intl.relativetimeformat.supportedlocalesof(locales[, options]) parameters locales a string with a bcp 47 language tag, or an array of such strings.
... return value an array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale.
... description returns an array with a subset of the language tags provided in locales.
JSON - JavaScript
description javascript and json differences json is a syntax for serializing objects, arrays, numbers, strings, booleans, and null.
... objects and arrays property names must be double-quoted strings; trailing commas are forbidden.
... full json syntax the full json syntax is as follows: json = null or true or false or jsonnumber or jsonstring or jsonobject or jsonarray jsonnumber = - positivenumber or positivenumber positivenumber = decimalnumber or decimalnumber .
...haracter except " or \ or u+0000 through u+001f or escapesequence escapesequence = \" or \/ or \\ or \b or \f or \n or \r or \t or \u hexdigit hexdigit hexdigit hexdigit hexdigit = 0 through 9 or a through f or a through f jsonobject = { } or { members } members = jsonstring : json or members , jsonstring : json jsonarray = [ ] or [ arrayelements ] arrayelements = json or arrayelements , json insignificant whitespace may be present anywhere except within a jsonnumber (numbers must contain no whitespace) or jsonstring (where it is interpreted as the corresponding character in the string, or would cause an error).
Math.max() - JavaScript
examples using math.max() math.max(10, 20); // 20 math.max(-10, -20); // -10 math.max(-10, 20); // 20 getting the maximum element of an array array.reduce() can be used to find the maximum element in a numeric array, by comparing each value: var arr = [1,2,3]; var max = arr.reduce(function(a, b) { return math.max(a, b); }); the following function uses function.prototype.apply() to get the maximum of an array.
... getmaxofarray([1, 2, 3]) is equivalent to math.max(1, 2, 3), but you can use getmaxofarray() on programmatically constructed arrays.
... this should only be used for arrays with relatively few elements.
... function getmaxofarray(numarray) { return math.max.apply(null, numarray); } the new spread operator is a shorter way of writing the apply solution to get the maximum of an array: var arr = [1, 2, 3]; var max = math.max(...arr); however, both spread (...) and apply will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters.
Object.prototype.constructor - JavaScript
objects created without the explicit use of a constructor function (such as object- and array-literals) will have a constructor property that points to the fundamental object constructor type for that object.
... let o = {} o.constructor === object // true let o = new object o.constructor === object // true let a = [] a.constructor === array // true let a = new array a.constructor === array // true let n = new number(3) n.constructor === number // true examples displaying the constructor of an object the following example creates a constructor (tree) and an object of that type (thetree).
... function type () {} let types = [ new array(), [], new boolean(), true, // remains unchanged new date(), new error(), new function(), function () {}, math, new number(), 1, // remains unchanged new object(), {}, new regexp(), /(?:)/, new string(), 'test' // remains unchanged ] for (let i = 0; i < types.length; i++) { types[i].constructor = type types[i] = [types[i].
...constructor, types[i] instanceof type, types[i].tostring()] } console.log(types.join('\n')) this example displays the following output (comments added for reference): function type() {},false, // new array() function type() {},false, // [] function type() {},false,false // new boolean() function boolean() { [native code] },false,true // true function type() {},false,mon sep 01 2014 16:03:49 gmt+0600 // new date() function type() {},false,error // new error() function type() {},false,function anonymous() { } // new function() function type() {},...
Object.getOwnPropertySymbols() - JavaScript
the object.getownpropertysymbols() method returns an array of all symbol properties found directly upon a given object.
... return value an array of all symbol properties found directly upon the given object.
... description similar to object.getownpropertynames(), you can get all symbol properties of a given object as an array of symbols.
... as all objects have no own symbol properties initially, object.getownpropertysymbols() returns an empty array unless you have set symbol properties on your object.
Object.keys() - JavaScript
the object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
... return value an array of strings that represent all the enumerable properties of the given object.
... description object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object.
... examples using object.keys // simple array const arr = ['a', 'b', 'c']; console.log(object.keys(arr)); // console: ['0', '1', '2'] // array-like object const obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.keys(obj)); // console: ['0', '1', '2'] // array-like object with random key ordering const anobj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(object.keys(anobj)); // console: ['2', '7', '100'] // getfoo is a property which isn't...
Object.values() - JavaScript
the object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop.
... return value an array containing the given object's own enumerable property values.
... description object.values() returns an array whose elements are the enumerable property values found on the object.
... examples using object.values const obj = { foo: 'bar', baz: 42 }; console.log(object.values(obj)); // ['bar', 42] // array-like object const arraylikeobj1 = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.values(arraylikeobj1 )); // ['a', 'b', 'c'] // array-like object with random key ordering // when using numeric keys, the values are returned in the keys' numerical order const arraylikeobj2 = { 100: 'a', 2: 'b', 7: 'c' }; console.log(object.values(arraylikeobj2 )); // ['b', 'c', 'a'] // getfoo is property which is...
Promise.allSettled() - JavaScript
the promise.allsettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.
... syntax promise.allsettled(iterable); parameters iterable an iterable object, such as an array, in which each member is a promise.
...at that time, the returned promise's handler is passed as input an array containing the outcome of each promise in the original set of promises.
... however, if and only if an empty iterable is passed as an argument, promise.allsettled() returns a promise object that has already been resolved as an empty array.
RegExp.prototype.exec() - JavaScript
returns a result array, or null.
... return value if the match succeeds, the exec() method returns an array (with extra properties index and input; see below) and updates the lastindex property of the regular expression object.
... the returned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text.
... for example, assume you have this script: let myre = /ab*/g; let str = 'abbcdefabh'; let myarray; while ((myarray = myre.exec(str)) !== null) { let msg = 'found ' + myarray[0] + '.
Set - JavaScript
(for sets, this is the same as the keys() method.) set.prototype.entries() returns a new iterator object that contains an array of [value, value] for each element in the set object, in insertion order.
...b": 2} for (let item of myset.keys()) console.log(item) // logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} for (let item of myset.values()) console.log(item) // logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} // (key and value are the same here) for (let [key, value] of myset.entries()) console.log(key) // convert set object to an array object, with array.from let myarr = array.from(myset) // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}] // the following will also work if run in an html document myset.add(document.body) myset.has(document.queryselector('body')) // true // converting between set and array myset2 = new set([1, 2, 3, 4]) myset2.size // 4 [...myset2] // [1, 2, 3, 4] //...
...turn _difference } // examples let seta = new set([1, 2, 3, 4]) let setb = new set([2, 3]) let setc = new set([3, 4, 5, 6]) issuperset(seta, setb) // => true union(seta, setc) // => set [1, 2, 3, 4, 5, 6] intersection(seta, setc) // => set [3, 4] symmetricdifference(seta, setc) // => set [1, 2, 5, 6] difference(seta, setc) // => set [1, 2] relation with array objects let myarray = ['value1', 'value2', 'value3'] // use the regular set constructor to transform an array into a set let myset = new set(myarray) myset.has('value1') // returns true // use the spread operator to transform a set into an array.
... console.log([...myset]) // will show you exactly the same array as myarray remove duplicate elements from the array // use to remove duplicate elements from the array const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5] console.log([...new set(numbers)]) // [2, 3, 4, 5, 6, 7, 32] relation with strings let text = 'india' let myset = new set(text) // set ['i', 'n', 'd', 'i', 'a'] myset.size // 5 //case sensitive & duplicate ommision new set("firefox") // set(7) [ "f", "i", "r", "e", "f", "o", "x" ] new set("firefox") // set(6) [ "f", "i", "r", "e", "o", "x" ] specifications specification ecmascript (ecma-262)the definition of 'set' in that specification.
String.prototype.match() - JavaScript
if you don't give any parameter and use the match() method directly, you will get an array with an empty string: [""].
... return value an array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.
...all letters a through e and a through e are returned, each its own element in the array.
... const str = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; const regexp = /[a-e]/gi; const matches_array = str.match(regexp); console.log(matches_array); // ['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e'] note: see also string.prototype.matchall() and advanced searching with flags.
String.prototype.matchAll() - JavaScript
instead, by using matchall, you get an iterator to use with the more convenient for...of, array spread, or array.from() constructs: const regexp = regexp('foo[a-z]*','g'); const str = 'table football, foosball'; const matches = str.matchall(regexp); for (const match of matches) { console.log(`found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`); } // expected output: "found football start=6 end=14." // expected output: "found foosball start=16 end=24." // matc...
...hes iterator is exhausted after the for..of iteration // call matchall again to create a new iterator array.from(str.matchall(regexp), m => m[0]); // array [ "football", "foosball" ] matchall will throw an exception if the g flag is missing.
... const regexp = regexp('[a-c]','g'); regexp.lastindex = 1; const str = 'abc'; array.from(str.matchall(regexp), m => `${regexp.lastindex} ${m[0]}`); // array [ "1 b", "1 c" ] better access to capturing groups (than string.prototype.match()) another compelling reason for matchall is the improved access to capture groups.
... capture groups are ignored when using match() with the global /g flag: let regexp = /t(e)(st(\d?))/g; let str = 'test1test2'; str.match(regexp); // array ['test1', 'test2'] using matchall, you can access capture groups easily: let array = [...str.matchall(regexp)]; array[0]; // ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4] array[1]; // ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4] specifications specification ecmascript (ecma-262)the definition of 'string.prototype.matchall' in that specification.
Symbol - JavaScript
finding symbol properties on objects the method object.getownpropertysymbols() returns an array of symbols and lets you find symbol properties on a given object.
... note that every object is initialized with no own symbol properties, so that this array will be empty unless you've set symbol properties on the object.
... symbol.isconcatspreadable a boolean value indicating if an object should be flattened to its array elements.
... used by array.prototype.concat().
WebAssembly.Memory() constructor - JavaScript
the webassembly.memory() constructor creates a new memory object whose buffer property is a resizable arraybuffer or sharedarraybuffer that holds the raw bytes of memory accessed by a webassembly instance.
...its buffer property will return an arraybuffer.
... webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); creating a shared memory by default, webassembly memories are unshared.
... you can create a shared memory by passing shared: true in the constructor's initialization object: let memory = new webassembly.memory({initial:10, maximum:100, shared:true}); this memory's buffer property will return a sharedarraybuffer.
WebAssembly.Memory - JavaScript
the webassembly.memory object is a resizable arraybuffer or sharedarraybuffer that holds the raw bytes of memory accessed by a webassembly instance.
...its buffer property will return an arraybuffer.
... webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); creating a shared memory by default, webassembly memories are unshared.
... you can create a shared memory by passing shared: true in the constructor's initialization object: let memory = new webassembly.memory({initial:10, maximum:100, shared: true}); this memory's buffer property will return a sharedarraybuffer.
WebAssembly.instantiate() - JavaScript
this function has two overloads: the primary overload takes the webassembly binary code, in the form of a typed array or arraybuffer, and performs both compilation and instantiation in one step.
...if at all possible, you should use the newer webassembly.instantiatestreaming() method instead, which fetches, compiles, and instantiates a module all in one step, directly from the raw bytecode, so doesn't require conversion to an arraybuffer.
... syntax primary overload — taking wasm binary code promise<resultobject> webassembly.instantiate(buffersource, importobject); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile.
... var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.instantiate(bytes, importobject) ).then(result => result.instance.exports.exported_func() ); note: you can also find this example at index.html on github (view it live also).
Image file type and format guide - Web media technologies
every value in a tiff file is specified using its tag (indicating what kind of information it is, such as the width of the image) and its type (indicating the format the data is stored in), followed by the length of the array of values to assign to that tag (all properties are stored in arrays, even for single values).
...for example, the width of an image, imagewidth, is stored using tag 0x0100, and is a one-entry array.
... xbm uses a snippet of c code to represent the contents of the image as an array of bytes.
... each image consists of 2 to 4 #define directives, providing the width and height of the bitmap (and optionally the hotspot, if the image is designed as a cursor), followed by an array of unsigned char, where each value contains 8 1-bit monochrome pixels.
Codecs used by WebRTC - Web media technologies
special parameter support requirements avc offers a wide array of parameters for controlling optional values.
...for example, to determine the supported codecs for video, you can do this: codeclist = rtcrtpsender.getcapabilities("video").codecs; now codeclist is an array of rtcrtpcodeccapability objects, each describing one codec configuration.
... on return, then, codeclist is either null to indicate that no video tracks were found or it's an array of rtcrtpcodecparameters objects, each describing one permitted codec configuration.
...zed during negotiation): function prefercodec(codecs, mimetype) { let othercodecs = []; let sortedcodecs = []; let count = codecs.length; codecs.foreach(codec => { if (codec.mimetype === mimetype) { sortedcodecs.push(codec); } else { othercodecs.push(codec); } }); return sortedcodecs.concat(othercodecs); } this code is just splitting the codec list into two arrays: one containing codecs whose mime type matches the one specified by the mimetype parameter, and the other with all the other codecs.
Fills and Strokes - SVG: Scalable Vector Graphics
finally, you can also use dashed line types on a stroke by specifying the stroke-dasharray attribute.
... <?xml version="1.0" standalone="no"?> <svg width="200" height="150" xmlns="http://www.w3.org/2000/svg" version="1.1"> <path d="m 10 75 q 50 10 100 75 t 190 75" stroke="black" stroke-linecap="round" stroke-dasharray="5,10,5" fill="none"/> <path d="m 10 75 l 190 75" stroke="red" stroke-linecap="round" stroke-width="1" stroke-dasharray="5,5" fill="none"/> </svg> the stroke-dasharray attribute takes a series of comma-separated numbers as its argument.
... there are additional stroke and fill properties available, including fill-rule, which specifies how to color in shapes that overlap themselves; stroke-miterlimit, which determines if a stroke should draw miters; and stroke-dashoffset, which specifies where to start a dasharray on a line.
...attributes that deal with painting and filling are usually available, so fill, stroke, stroke-dasharray, etc...
XPath snippets - XPath
example: defining a custom node-specific evaluatexpath() utility function // evaluate an xpath expression aexpression against a given dom node // or document object (anode), returning the results as an array // thanks wanderingstan at morethanwarm dot mail dot com for the // initial work.
...ults[i].value); // get the 2nd person node results = evaluatexpath(people, "/people/person[2]"); // get all the person nodes that have addresses in denver results = evaluatexpath(people, "//person[address/@city='denver']"); // get all the addresses that have "south" in the street name results = evaluatexpath(people, "//address[contains(@street, 'south')]"); alert(results.length); docevaluatearray the following is a simple utility function to get (ordered) xpath results into an array, regardless of whether there is a special need for namespace resolvers, etc.
... it avoids the more complex syntax of document.evaluate() for cases when it is not required as well as the need to use the special iterators on xpathresult (by returning an array instead).
... example: defining a simple docevaluatearray​() utility function // example usage: // var els = docevaluatearray('//a'); // alert(els[0].nodename); // gives 'a' in html document with at least one link function docevaluatearray (expr, doc, context, resolver) { var i, result, a = []; doc = doc || (context ?
Compiling an Existing C Module to WebAssembly - WebAssembly
looking at the encoding api of libwebp, you'll find that it expects an array of bytes in rgb, rgba, bgr or bgra.
... luckily, the canvas api has canvasrenderingcontext2d.getimagedata — that gives you an uint8clampedarray containing the image data in rgba: async function loadimage(src) { // load image const imgblob = await fetch(src).then(resp => resp.blob()); const img = await createimagebitmap(imgblob); // make canvas same size as image const canvas = document.createelement('canvas'); canvas.width = img.width; canvas.height = img.height; // draw image onto canvas const ctx = canvas.getcontext('2d'); ctx.drawimage(img, 0, 0); return ctx.getimagedata(0, 0, img.width, img.height); } now it's "only" a matter of copying the data from javascript into wasm.
...because functions in c can't have arrays as return types (unless you allocate memory dynamically), this example resorts to a static global array.
...size() { return result[1]; } now with all of that in place, you can call the encoding function, grab the pointer and image size, put it in a javascript buffer of your own, and release all the wasm buffers allocated in the process: api.encode(p, image.width, image.height, 100); const resultpointer = api.get_result_pointer(); const resultsize = api.get_result_size(); const resultview = new uint8array(module.heap8.buffer, resultpointer, resultsize); const result = new uint8array(resultview); api.free_result(resultpointer); note: new uint8array(somebuffer) will create a new view onto the same memory chunk, while new uint8array(sometypedarray) will copy the data.
Loading Content Scripts - Archive of obsolete content
the constructors for content-script-using objects such as panel and page-mod define a group of options for loading content scripts: contentscript string, array contentscriptfile string, array contentscriptwhen string contentscriptoptions object we have already seen the contentscript option, which enables you to pass in the text of the script itself as a string literal.
...contentscriptfile: data.url("my-content-script.js") both contentscript and contentscriptfile accept an array of strings, so you can load multiple scripts, which can also interact directly with each other in the content process: // "data" is supplied by the "self" module var data = require("sdk/self").data; ...
... any kind of jsonable value (object, array, string, etc.) can be used here.
simple-prefs - Archive of obsolete content
usage defining and initializing preferences to define preferences and give them initial values, add a new json array called preferences to your package.json file, and give it one entry for each preference: { "fullname": "example add-on", ...
... the options are specified by a mandatory "options" attribute, that is an array of objects with mandatory attributes "label" and "value" the values of the "value" attributes must be supplied as strings.
... the options are specified by a mandatory "options" attribute, that is an array of objects with mandatory attributes "label" and "value" the values of the "value" attributes must be supplied as strings.
core/promise - Archive of obsolete content
for example grouping promises to observe single resolution of all of them is as simple as this: var group = promised(array); var abc = group(aasync, basync, casync).then(function(items) { return items[0] + items[1] + items[2]; }); all the all function is provided to consume an array of promises and return a promise that will be accepted upon the acceptance of all the promises in the initial array.
... this can be used to perform an action that requires values from several promises, like getting user information and server status, for example: const { all } = require('sdk/core/promise'); all([getuser, getserverstatus]).then(function (result) { return result[0] + result[1] }); if one of the promises in the array is rejected, the rejection handler handles the first failed promise and remaining promises remain unfulfilled.
...in the following example we implement functions that take multiple promises and return one that resolves to first one being fulfilled: function race() { let { promise, resolve } = defer(); array.slice(arguments).foreach(function(promise) { promise.then(resolve); }); return promise; } var asyncaorb = race(readasync(urla), readasync(urlb)); note: that this implementation forgives failures and would fail if all promises fail to resolve.
ui/toolbar - Archive of obsolete content
optional options: name type items array adding buttons to toolbars is only supported from firefox 30 onwards.
... an array of items to appear in the toolbar.
... items the array of frames hosted by this toolbar.
Creating annotations - Archive of obsolete content
in the attach handler we do three things: send the content script a message with the current activation status add the worker to an array called selectors so we can send it messages later on assign a message handler for messages from this worker.
...if the message is detach we remove the worker from the selectors array.
... at the top of the file import the page-mod module and declare an array for the workers: var pagemod = require('sdk/page-mod'); var selectors = []; add detachworker(): function detachworker(worker, workerarray) { var index = workerarray.indexof(worker); if(index != -1) { workerarray.splice(index, 1); } } edit toggleactivation() to notify the workers of a change in activation state: function activateselectors() { selectors.foreach( function (selector) { selector.postmessage(annotatorison); }); } function toggleactivation() { annotatorison = !annotatorison; activateselectors(); return annotatorison; } we'll be using this url in all our screenshots.
Storing annotations - Archive of obsolete content
first, import the simple-storage module with a declaration like: var simplestorage = require('sdk/simple-storage'); in the module scope, initialize an array which will contain the stored annotations: if (!simplestorage.storage.annotations) simplestorage.storage.annotations = []; now we'll add a function to the module scope which deals with a new annotation.
...(); event.preventdefault(); self.postmessage(storedannotation.url); }); annotationhtml.find('.selection-text') .text(storedannotation.anchortext); annotationhtml.find('.annotation-text') .text(storedannotation.annotationtext); annotationlist.append(annotationhtml); }); }); it builds the dom for the panel from the array of annotations it is given.
... when the panel is shown we send it the array of stored annotations.
Creating Reusable Modules - Archive of obsolete content
var s = array.from(hash, (c, i) => tohexstring(hash.charcodeat(i))).join(""); return s; } putting it together the complete add-on adds a button to firefox: when the user clicks the button, we ask them to select a file, compute the hash, and log the hash to the console: var {cc, ci} = require("chrome"); // return the two-digit hexadecimal code for a byte function tohexstring(charcode) { return ("0...
... var s = array.from(hash, (c, i) => tohexstring(hash.charcodeat(i))).join(""); return s; } function promptforfile() { var window = require("sdk/window/utils").getmostrecentbrowserwindow(); const nsifilepicker = ci.nsifilepicker; var fp = cc["@mozilla.org/filepicker;1"] .createinstance(nsifilepicker); fp.init(window, "select a file", nsifilepicker.modeopen); fp.appendfilters(nsifile...
... var s = array.from(hash, (c, i) => tohexstring(hash.charcodeat(i))).join(""); return s; } exports.hashfile = md5file; index.js finally, update index.js to import these two new modules and use them: var filepicker = require("./filepicker.js"); var md5 = require("./md5.js"); require("sdk/ui/button/action").actionbutton({ id: "show-panel", label: "show panel", icon: { "16": "./icon-16.png" ...
Drag & Drop - Archive of obsolete content
pported) dragsession.candrop = true; } function _dragdrop(aevent) { var dragservice = components.classes["@mozilla.org/widget/dragservice;1"].getservice(components.interfaces.nsidragservice); var dragsession = dragservice.getcurrentsession(); var _ios = components.classes['@mozilla.org/network/io-service;1'].getservice(components.interfaces.nsiioservice); var uris = new array(); // if sourcenode is not null, then the drop was from inside the application if (dragsession.sourcenode) return; // setup a transfer item to retrieve the file data var trans = components.classes["@mozilla.org/widget/transferable;1"].createinstance(components.interfaces.nsitransferable); trans.adddataflavor("text/x-moz-url"); trans.adddataflavor("application/x-mo...
...terfaces.nsisupportsstring); } catch(ex) { } if (str) { uri = _ios.newuri(str.data.split("\n")[0], null, null); } else { var file = data.value.queryinterface(components.interfaces.nsifile); if (file) uri = _ios.newfileuri(file); } } if (uri) uris.push(uri); } // use the array of file uris } the _dragover function checks the drag data to see if a simple text file or general purpose file types are available.
...the _dragdrop function retrieves the file uri data from the drag session and creates an array of file uris that the xul application can use.
File I/O - Archive of obsolete content
enumerating files in given directory the snippet below makes an array of nsifiles corresponding to sub-directories/"sub-files" of the given directory.
... // file is the given directory (nsifile) var entries = file.directoryentries; var array = []; while(entries.hasmoreelements()) { var entry = entries.getnext(); entry.queryinterface(components.interfaces.nsifile); array.push(entry); } reading from a file read into a stream or a string this will allow you to read a file without locking up the ui thread while reading.
... createinstance(components.interfaces.nsifileinputstream); istream.init(file, 0x01, 0444, 0); istream.queryinterface(components.interfaces.nsilineinputstream); // read lines into array var line = {}, lines = [], hasmore; do { hasmore = istream.readline(line); lines.push(line.value); } while(hasmore); istream.close(); // do something with read data alert(lines); reading a binary file for instance, to get the data in a png file: var ios = components.classes["@mozilla.org/network/io-service;1"].
JavaScript Daemons Management - Archive of obsolete content
t(func, delay, [param1, param2, ...]); |*| var timeoutid = window.settimeout(code, delay); |*| var intervalid = window.setinterval(func, delay[, param1, param2, ...]); |*| var intervalid = window.setinterval(code, delay); |*| \*/ /* if (document.all && !window.settimeout.ispolyfill) { var __nativest__ = window.settimeout; window.settimeout = function (vcallback, ndelay) { var aargs = array.prototype.slice.call(arguments, 2); return __nativest__(vcallback instanceof function ?
... function () { vcallback.apply(null, aargs); } : vcallback, ndelay); }; window.settimeout.ispolyfill = true; } if (document.all && !window.setinterval.ispolyfill) { var __nativesi__ = window.setinterval; window.setinterval = function (vcallback, ndelay) { var aargs = array.prototype.slice.call(arguments, 2); return __nativesi__(vcallback instanceof function ?
... daemon.construct(arrayofarguments) returns a new daemon constructed upon an array of arguments.
Code snippets - Archive of obsolete content
stringview a library that implements a stringview view for javascript typed arrays.
... this lets you access data in typed arrays using c-like string functions.
...nevertheless, the increasing computational power of modern browsers together with the introduction of typed arrays in ecmascript allow us, in theory, to build full virtual machines in pure ecmascript.
MMgc - Archive of obsolete content
alloc is often used to allocate arrays and other objects of variable size that contain gc pointers or are otherwise desirable to have in managed memory.
...this could be a significant speedup if the black object was a large array getting populated with a bunch of new objects.
... on the other hand if the black is a huge array and only a couple slots had new objects written to them we are wasting time by marking the whole thing.
Drag and Drop - Archive of obsolete content
the function invokedragsession takes four parameters, as described below: invokedragsession(element, transferablearray, region, actions) element a reference to the element that is being dragged.
... transferablearray an array of nsitransferable objects, one for each item being dragged.
... an array is used because you might want to drag several objects at once, such as a set of files.
Venkman Internals - Archive of obsolete content
the full text of the file can be found in an array located at scriptwrapper.scriptinstance.sourcetext.lines.
... this array is 0 based, of course.
...a scriptmanager keeps all of the loaded instances of a particular url in the scriptmanager.instances array, in the order that they were loaded.
Writing to Files - Archive of obsolete content
if you want to write a negative value, use the following calculation first to convert the value: function writenegative(val) { if (val > 0x7fff) val = ~(0x10000 - val - 1); stream.write16(val); } one last method that is useful for writing to binary streams is the writebytearray method, used to write an array of bytes.
... this method takes an array of values and writes them all in sequence, where each element in the array is written as one byte.
... stream.writebytearray([25, 77, 46, 8]); this example uses the writebytearray method to write 4 bytes to the stream.
appendNotification - Archive of obsolete content
buttons - array of button descriptions to appear on the notification.
... priority levels (defined as properties of notificationbox) : priority_info_low priority_info_medium priority_info_high priority_warning_low priority_warning_medium priority_warning_high priority_critical_low priority_critical_medium priority_critical_high priority_critical_block buttons : the buttons argument is an array of button descriptions.
...if no button has this set, the first button in the array is the default.
replaceGroup - Archive of obsolete content
« xul reference home replacegroup( group ) not in firefox return type: array of session history objects replaces existing tabs with a new set.
...the argument should be an array of objects, one for each document to load.
...this method returns an array of the session history objects for the tabs that were removed.
XBL Example - Archive of obsolete content
<property name="page" onget="return parseint(document.getanonymousnodes(this)[0].childnodes[0].getattribute('selectedindex'));" onset="return this.setpage(val);"/> the page property gets its value by looking at the first element of the anonymous array.
...the anonymous array isn't used as the deck is not anonymous from the box.
... var thedeck=document.getanonymousnodes(this)[0].childnodes[0]; get the first element of the anonymous content array, which will be the vertical box, then get its first child, which will be the deck element.
notificationbox - Archive of obsolete content
buttons - array of button descriptions to appear on the notification.
... priority levels (defined as properties of notificationbox) : priority_info_low priority_info_medium priority_info_high priority_warning_low priority_warning_medium priority_warning_high priority_critical_low priority_critical_medium priority_critical_high priority_critical_block buttons : the buttons argument is an array of button descriptions.
...if no button has this set, the first button in the array is the default.
NPN_Enumerate - Archive of obsolete content
identifiers a pointer to receive a pointer to the start of an array of string identifiers of the names of the properties and methods of npobj.
... note: the caller must call npn_memfree() on the pointer received through the identifiers parameter of a successful call to npn_enumerate to release the array of string identifiers when it is no longer needed.
... the callee allocates this array via npn_memalloc().
NPN_Invoke - Archive of obsolete content
args an array of arguments to pass to the method.
... argcount the number of arguments in the args array.
...description the method arguments are passed as an array of npvariants, and the number of arguments is passed in.
NPN_InvokeDefault - Archive of obsolete content
args an array of arguments to pass to the default method.
... argcount the number of arguments in the args array.
...description the method arguments are passed as an array of npvariants, and the number of arguments is passed in.
Adobe Flash - Archive of obsolete content
<script type="text/javascript">identifyflash();</script> typically, javascript code that determines what version of the plugin is installed looks at the mimetypes array that is part of the navigator object.
...tokenize description string to its constituent parts var versionarray = description.match(/[\d.]+/g); // 2.
...the description string is broken into an array of constituent strings based on an invocation of the match method with a regular expression that assumes that the string format will be in the format flash major rminor where major can be a major revision such as "5" or "6" and minor is the subsidiary version number.
New in JavaScript 1.7 - Archive of obsolete content
javascript 1.7 is a language update introducing several new features, in particular generators, iterators, array comprehensions, let expressions, and destructuring assignment.
...the features that do not introduce new keywords (destructuring assignment and array comprehensions) can be used without specifying the javascript version.
... iterators and generators array comprehensions let statement (support for let expression was dropped in gecko 41, see bug 1023609).
ECMAScript 2015 support in Mozilla - Archive of obsolete content
standard library additions to the array object array iteration with for...of (firefox 13) array.from() (firefox 32) array.of() (firefox 25) array.prototype.fill() (firefox 31) array.prototype.find(), array.prototype.findindex() (firefox 25) array.prototype.entries(), array.prototype.keys() (firefox 28), array.prototype.values() array.prototype.copywithin() (firefox 32) get array[@@species] (firefox 48) new map and set o...
...s (firefox 40) new symbol object symbol (firefox 36) symbol.iterator (firefox 36) symbol.for() - global symbol registry (firefox 36) symbol.match (firefox 40) symbol.species (firefox 41) symbol.toprimitive (firefox 44) symbol.prototype[@@toprimitive] (firefox 44) symbol.replace (firefox 49) symbol.search (firefox 49) symbol.split (firefox 49) symbol.hasinstance (firefox 50) typed arrays typed arrays are specified as part of ecmascript 2015 and no longer in their own specification.
... arraybuffer get arraybuffer[@@species] (firefox 48) dataview int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array get %typedarray%[@@species] (firefox 48) expressions and operators new.target (firefox 41) spread operator for arrays (firefox 16) use symbol.iterator property (firefox 36) spread operator for function calls (firefox 27) use symbol.iterator property (firefox 36) const (js 1.5, firefox 1.0) (es2015 compliance bug 950547 implemented in firefox 51) let (js 1.7, firefox 2) (es2015 compliance bug 950547 implemented in firefox 51) destructuring assignment (js 1.7, firefox 2) (es2015 compliance bug 1055984) statements for...of (firefox 13) works in terms of .iterator() and ...
New in JavaScript - Archive of obsolete content
includes ecmascript for xml (e4x), new array methods plus string and array generics.
... includes generators, iterators, array comprehensions, let expressions, and destructuring assignment.
... includes expression closures, generator expressions and array.reduce() javascript 1.8.1 version shipped in firefox 3.5.
Object.prototype.__noSuchMethod__ - Archive of obsolete content
} id the name of the non-existent method that was called args an array of the arguments passed to the method description by default, an attempt to call a method that doesn't exist on an object results in a typeerror being thrown.
...the function takes two arguments, the first is the name of the method attempted and the second is an array of the arguments that were passed in the method call.
... the second argument is an actual array (that is, it inherits through the array.prototype chain) and not the array-like arguments object.
Object.observe() - Archive of obsolete content
callback the function called each time changes are made, with the following argument: changes an array of objects each representing a change.
...if omitted, the array ["add", "update", "delete", "reconfigure", "setprototype", "preventextensions"] will be used.
... description callback is called each time a change is made to obj, with an array of all changes in the order in which they occurred.
Reference - Archive of obsolete content
alert(array.myfunction); //available in array (array cannot be prototyped) object -> function -> instance but there is another but...
...a subset of the "object > (function, everything else)" chain could be object > function > (object, function, array, string, boolean, number, date, regexp, error).
... array, for example, as a constructor function is an instance of the function object, which happens to be an instance of object; therefore, array is also an instance of object.
Archived open Web documentation - Archive of obsolete content
talk:array.foreach() ok, in the end i didn't remove the old code as it isn't hosted anywhere (i thought the github reference contained the code) but inserted a faster implementation above while retaining the rest of the document.
... parallelarray the goal of parallelarray was to enable data-parallelism in web applications.
... the higher-order functions available on parallelarray attempted to execute in parallel, though they may fall back to sequential execution if necessary.
Describing microformats in JavaScript - Archive of obsolete content
required an array indicating the names of any properties that must be specified.
...if a property is plural, it is returned as an array.
...this allows multiple lines of address information to be contained in the street-address array.
Square tilemaps implementation: Static maps - Game development
tiles: a 1-dimensional array containing the visual grid.
...however, it's usually more common to represent the grid with a 1-dimensional array.
... in this case, we need to map the column and row to an array index: var index = row * map.cols + column; wrapping up, an example of a tilemap object could look like the following.
Build the brick field - Game development
setting up the brick variables the overall aim of this lesson is to render a few lines of code for the bricks, using a nested loop that works through a two-dimensional array.
... we will hold all our bricks in a two-dimensional array.
... brick drawing logic now let's create a function to loop through all the bricks in the array and draw them on the screen.
Animations and tweens - Game development
tion next up, go into your create() function, find the line that loads the ball sprite, and below it put the call to animations.add() seen below: ball = game.add.sprite(50, 250, 'ball'); ball.animations.add('wobble', [0,1,0,2,0,1,0,2,0], 24); to add an animation to the object we use the animations.add() method, which contains the following parameters the name we chose for the animation an array defining the order in which to display the frames during the animation.
...phaser extracts these and stores references to them in an array — positions 0, 1, and 2.
... the above array says that we are displaying frame 0, then 1, then 0, etc.
How to build custom form controls - Learn web development
the object returned by the queryselectorall() function is a nodelist rather than an array.
... this is important because array objects support the foreach function, but nodelist doesn't.
... because nodelist really looks like an array and because foreach is so convenient to use, we can easily add the support of foreach to nodelist in order to make our life easier, like so: nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } if you need to support legacy browsers, ensure the browsers support these features.
Introducing asynchronous JavaScript - Learn web development
an example is when we use array.prototype.foreach() to loop through the items in an array (see it live, and the source): const gods = ['apollo', 'artemis', 'ares', 'zeus']; gods.foreach(function (eachname, index){ console.log(index + '.
... ' + eachname); }); in this example we loop through an array of greek gods and print the index numbers and values to the console.
... the expected parameter of foreach() is a callback function, which itself takes two parameters, a reference to the array name and index values.
Client-side storage - Learn web development
for this simple example, we've stored the names of the videos to fetch in an array of objects: const videos = [ { 'name' : 'crystal' }, { 'name' : 'elf' }, { 'name' : 'frog' }, { 'name' : 'monster' }, { 'name' : 'pig' }, { 'name' : 'rabbit' } ]; to start with, once the database is successfully opened we run an init() function.
...this takes one argument — references to all the individual promises you want to check for fulfillment placed in an array — and is itself promise-based.
... when all those promises have fulfilled, the all() promise fulfills with an array containing all the individual fulfillment values.
JavaScript First Steps - Learn web development
after that, we discuss some key building blocks in detail, such as variables, strings, numbers and arrays.
... arrays in the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name.
... here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
Object building practice - Learn web development
avoid drawing errors random(0 + size,width - size), random(0 + size,height - size), random(-7,7), random(-7,7), 'rgb(' + random(0,255) + ',' + random(0,255) + ',' + random(0,255) +')', size ); balls.push(ball); } the while loop creates a new instance of our ball() using random values generated with our random() function, then push()es it onto the end of our balls array, but only while the number of balls in the array is less than 25.
... loops through all the balls in the balls array, and runs each ball's draw() and update() function to draw each one on the screen, then do the necessary updates to position and velocity in time for the next frame.
...to do this, we start another for loop to loop through all the balls in the balls[] array.
Test your skills: Object basics - Learn web development
albums: an array representing the albums released by the band.
... each array item should be an object containing the following members: name: a string representing the name of the album.
... include at least two albums in the albums array.
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
in todo-data.js, add the following getter underneath the existing all() getter to define what the incomplete todos actually are: get incomplete() { return this.todos.filter(todo => { return todo.iscompleted === false; }); } using array.filter(), we declare that "incomplete" todos are ones that have iscompleted equal to false.
... next, add the following action underneath the existing add(text) action: @action clearcompleted() { this.todos = this.incomplete; } this is rather nice for clearing the todos — we just need to set the todos array to equal the list of incomplete todos.
... first of all, replace this line: <strong>0</strong> todos left with this, which populates the incomplete number with the length of the incomplete array: <strong>{{this.todos.incomplete.length}}</strong> todos left next, replace this: <button type="button" class="clear-completed"> with this: <button type="button" class="clear-completed" {{on 'click' this.todos.clearcompleted}}> so now when the button is clicked, the clearcompleted() action we added earlier is run.
Accessibility in React - Learn web development
we also pass an array into useeffect() as a second argument.
... this array is a list of values useeffect() should depend on.
...constant, we can update our useeffect() hook to implement the pseudocode we discussed before — update it as follows: useeffect(() => { if (!wasediting && isediting) { editfieldref.current.focus(); } if (wasediting && !isediting) { editbuttonref.current.focus(); } }, [wasediting, isediting]); note that the logic of useeffect() now depends on wasediting, so we provide it in the array of dependencies.
Communicating with frame scripts
because a single message can be received by more than one listener, the return value of sendsyncmessage() is an array of all the values returned from every listener, even if it only contains a single value: // frame script addeventlistener("click", function (event) { var results = sendsyncmessage("my-addon@me.org:my-e10s-extension-message", { details : "they clicked", tag : event.target.tagname }); content.console.log(results[0]); // "value from chrome" }, false); like arguments, return values...
... for example, suppose we load a script into the current <browser> on some event, and keep the browser message manager in an array, so we can send it messages: var messagemanagers = []; ...
... // on some event var browsermm = gbrowser.selectedbrowser.messagemanager; browsermm.loadframescript("chrome://my-addon@me.org/content/frame-script.js", false); messagemanagers.push(browsermm); console.log(messagemanagers.length); we can listen for message-manager-disconnect to update the array when the message managers disconnect (for example because the user closed the tab): function myobserver() { } myobserver.prototype = { observe: function(subject, topic, data) { var index = messagemanagers.indexof(subject); if (index != -1) { console.log("one of our message managers disconnected"); mms.splice(index, 1); } }, register: function() { var observerservice = cc["@mozilla.org/observer-service;1"] .getservice(ci.nsiobserverservice); ...
HTML parser threading
for a chat app.) some tree ops hold char or prunichar arrays.
... those arrays are allocated when creating the tree op and delete[]d by the destructor of nshtml5treeoperation.
... hence, data gets copied to and from these arrays.
IME handling guide
and editor sets these ime selections from mozilla::textrangetype which are sent by mozilla::widgetcompositionevent as mozilla::textrangearray.
... mtextrectarray::mstart if there is composition, mstart is same as mcompositionstart.
... mtextrectarray::mrects each character rects of composition string.
Extending a Protocol
include protocol pwindowglobal; namespace mozilla { namespace dom { async refcounted protocol pecho { manager pwindowglobal; parent: async echo(nscstring data) returns (nscstring aresult); async __delete__(); }; } // namespace dom } // namespace mozilla now, edit "./dom/ipc/moz.build" file and add 'pecho.ipdl', to the ipdl_sources array.
... private: ~echochild() = default; bool mactoralive; }; } // end of namespace dom } // end of namespace mozilla and add the echochild.h to dom/ipc/moz.build, as part of the exports.mozilla.dom array.
... echoparent::echoresolver&& aresolver); mozilla::ipc::ipcresult recv__delete__() override; void actordestroy(actordestroyreason awhy) override; private: ~echoparent() = default; bool mactoralive; }; } // end of namespace dom } // end of namespace mozilla #endif now, and add the echoparent.h to dom/ipc/moz.build, as part of the exports.mozilla.dom array.
Creating localizable web applications
the language_config class expects arrays of valid languages & supported languages.
...good: css: html[dir='rtl'] foo { /* rtl-specific rules for the foo element */ } body.rtl foo { /* rtl-specific rules for the foo element */ } html/php: <?php function isrtl($locale) { $rtl_locales = array('ar', 'fa', 'he'); return in_array($locale, $rtl_locales); } ?> <html lang="<?= $locale?>" dir="<?= isrtl($locale) ?
...good: $tab_labels = array( "popular" => _('popular'), "recent" => _('recent'), "all" => _('all'), "my" => _('my'), "favorites" => _('favorites') ); list($category, $tab, $page) = explode('/', $path); if ($tab == 'popular') { // $tab is always english // ....
Localization formats
that content is placed into an array that is used by the php code later.
... $array["getting started"] = "débuter avec firefox" the php code searches the array and returns the translation that is associated with the english term used by the web developer.
... <h1><?php echo ___("getting started")?></h1> function ___($str) { return $array[$str]; } advantage to .lang simple work-flow allowing the web developer to place the file in svn and it can appear on the staging server .lang syntax is like simplified .po, which many localizers who are familiar with linux and other projects understand mozilla has a basic tool called main.lang checker, which can show any untranslated files to the localizer no need to compile to .mo file so a localizer can see his/her changes more quickly creating simple diffs .lang files will be cached which will reduce any slowness effect disadvantage to .lang no plural forms no context for localizers unless you provide good comments no styling by localizers if it is needed may be ...
AsyncTestUtils extended framework
xpcomhdrarray [getter] return an nsimutablearray of the message headers that have been injected into folders.
... folderswithxpcomhdrarrays [getter] same as folderswithmsghdrs but the second element in each sub-list is an nsimutablearray instead of a js list.
... slice(...) uses the js array.slice semantics to slice the set.
Rhino shell
arguments the arguments object is an array containing the strings of all the arguments given at the command line when the shell was invoked.
... the following properties of the option object are processed: args - provides an array of additional command arguments env - explicit environment object.
... js> runcommand("bad_command", "--bad-arg", opt) js: "<stdin>", line 18: uncaught javascript exception: java.io.ioexception: bad_command: not found js> // passing explicit environment to the system shell js> runcommand("sh", "-c", "echo $env1 $env2", { env: {env1: 100, env2: 200}}) 100 200 0 js> // use args option to provide additional command arguments js> var arg_array = [1, 2, 3, 4]; js> runcommand("echo", { args: arg_array}) 1 2 3 4 0 examples for windows are similar: js> // invoke shell command js> runcommand("cmd", "/c", "date /t") 27.08.2005 0 js> // run sort collectiong the output js> var opt={input: "c\na\nb", output: 'sort output:\n'} js> runcommand("sort", opt) 0 js> print(opt.output) sort output: a b c js> // invoke notepad and wait until it exits ...
GC Rooting Guide
if you use these types directly, or create classes, structs or arrays that contain them, you must follow the rules set out in this guide.
... } return obj; } autorooters gc thing pointers that appear as part of a stack-allocated aggregates (array, structure, class, union) should use js::rooted<t> when possible.
... here are the main autorooters defined: type autorooter class js::value[] autoarrayrooter js::vector<js::value> autovaluevector js::vector<jsid> autoidvector js::vector<jsobject*> autoobjectvector js::vector<jsscript*> autoscriptvector if your case is not covered by one of these, it is possible to write your own by deriving from js::customautorooter and overriding the virtual trace() method.
How to embed the JavaScript engine
and say: ok = js_definefunctions(cx, global, my_functions); how to call javascript functions from c first, create arguments for the call, here i create arguments with 2 items: // [spidermonkey 24] js::autovaluearray is not defined.
... // js::autovaluevector argv(cx); // argv.resize(2); js::autovaluearray<2> argv(cx); argv[0].setint32(1); argv[1].setint32(2); then call the function: // [spidermonkey 24] pass arguments length and the 'jsval *' pointer.
... // js_callfunctionname(cx, global, "func", 2, argv.begin(), rval.address()); js_callfunctionname(cx, global, "func", argv, &rval); example say the click event is for the top-most or focused ui element at position (x, y): jsobject *target, *event; js::autovaluearray<1> argv(cx); /* * find event target and make event object to represent this click.
64-bit Compatibility
irsh i64, i32 i64 qursh i64, i32 i64 qcmov i32, i64, i64 i32 qior i64, i64 i64 qixor i64, i64 i64 qiaddp i64, i64 i64 qeq - quge i64, i64 i32 qcall n/a i64 extending or truncating native integers sometimes it is necessary to reduce a native integer to a 32-bit integer (for example, array or string lengths in tracemonkey) or extend a 32-bit integer to a native integer.
...for example, this code tries to load an index from an integer array, but it is not portable: lir->insload(lir_ldp, lir->ins2(lir_piadd, arrayins, lir->ins2i(lir_mul, indexins, sizeof(int)) ), 0); the sanityfilter will assert on a 64-bit platform because lir_piadd (which will be lir_qiadd) needs both operands to be 64-bit.
... the correct code is, assuming the index is unsigned: lir->insload(lir_ldp, lir->ins2(lir_piadd, arrayins, lir->ins_u2p(lir->ins2i(lir_mul, indexins, sizeof(int))) ), 0); what's pointer-width in tracerecorder?
Statistics API
slices: array of objects - a list of objects describing each slice in detail.
...the slices array describes how long each slice took and what work was done during the slice.
... each element of the slices array is an object with these fields: slice: integer - the slice index, starting at 0.
Garbage collection
an arena is one page (4096 bytes on almost all platforms) and contains an arenaheader, a few pad bytes, and then an array of aligned elements.
...heapslot (and the related class heapslotarray) is the same, but for object slots.
...the private field itself is opaque to the engine, but it may point to things that need to be marked, e.g., an array of jsobject pointers.
JS::Call
syntax bool js::call(jscontext *cx, js::handleobject thisobj, js::handlefunction fun, const js::handlevaluearray &args, js::mutablehandlevalue rval); bool js::call(jscontext *cx, js::handleobject thisobj, const char *name, const js::handlevaluearray& args, js::mutablehandlevalue rval); bool js::call(jscontext *cx, js::handleobject thisobj, js::handlevalue fun, const js::handlevaluearray& args, js::mutablehandlevalue rval); bool js::call(jscontext *cx, js::handlevalue thisv, js::handlevalue fun, const js::handlevaluearray& args, js::mutablehandlevalue rval); bool js::call(jscontext *cx, js::handlevalue thisv, js::handleobject funobj, const js::hand...
...levaluearray& args, js::mutablehandlevalue rval); name type description cx jscontext * pointer to a js context from which to derive runtime information.
... args js::handlevaluearray &amp; arguments to pass to the function.
JSPrincipals
obsolete since jsapi 13 getprincipalarray void * (*)(jscontext *, jsprincipals *) pointer to the function that returns an array of principal definitions.
... getprincipalarray is a pointer to the function that retrieves the principals for this object or script.
... see also mxr id search for jsprincipals js_newglobalobject js_holdprincipals js_dropprincipals bug 715417 - removed getprincipalarray and globalprivilegesenabled bug 728250 - added dump method, removed codebase, destroy, and subsume properties bug 884676 - changed refcount type to mozilla::atomic ...
JS_CallFunction
syntax /* added in spidermonkey 31 */ bool js_callfunction(jscontext *cx, js::handleobject obj, js::handlefunction fun, const js::handlevaluearray& args, js::mutablehandlevalue rval); bool js_callfunctionname(jscontext *cx, js::handleobject obj, const char *name, const js::handlevaluearray& args, js::mutablehandlevalue rval); bool js_callfunctionvalue(jscontext *cx, js::handleobject obj, js::handlevalue fval, const js::handlevaluearray& args, js::mutablehandlevalue rval); /* obsolete since jsapi 30 */ bool js_callfunction(jscontext *cx, jsobject *obj, jsfunction *fun, unsigned argc, jsval *argv, jsval *rval); bool js_callfunctionname(jscontext *cx, jsobject *obj, const...
... args const js::handlevaluearray &amp; reference to the array of argument values to pass to the function.
...obsolete since jsapi 30 argv jsval * pointer to the array of argument values to pass to the function.
JS_ConstructObject
argv jsval * (only in js_constructobjectwitharguments) the array of arguments to pass to the constructor.
...otherwise, the first argc elements of this array must be populated with valid jsval values.
... the caller does not need to ensure that the array elements are rooted.
JS_EncodeString
description js_encodestring and js_encodestringtoutf8 convert the specified javascript str to a c string (an array of 8-bit chars).
... the array returned by js_encodestring on success is allocated as though by a call to js_malloc.
... on success, js_encodestring and js_encodestringtoutf8 return a pointer to the char array, which is null-terminated.
JS_ExecuteRegExp
test bool pass true to avoid creating match result array and store boolean value to rval.
...receives the result match result array or boolean value.
... if test is false, js_executeregexp and js_newregexpobjectnostatics store the match result array to *rval if matches, otherwise stores null to *rval.
JS_GetParent
objects created by standard library functions, such as array.prototype.concat, have the global object as their parent.
... an object created by a script via implicit conversion (the ecmascript toobject operator), an object initializer ({a: 1, b: 2}), or an array initializer ([1, 2, 3]), has the global object as its parent.
... the initial parent of an object created via the jsapi depends on the particular jsapi function (of which there are many that create objects, including but not limited to js_newobject, js_constructobject, js_defineobject, js_valuetoobject, js_newarrayobject, js_newscriptobject, js_newfunction, js_compilefunction, js_definefunction, js_definefunctions, and js_initclass).
JS_New
syntax jsobject * js_new(jscontext *cx, js::handleobject ctor, const js::handlevaluearray& args); // added in jsapi 32 jsobject * js_new(jscontext *cx, jsobject *ctor, unsigned argc, jsval *argv); // obsolete since jsapi 32 name type description cx jscontext * the context in which to create the new object.
... args js::handlevaluearray &amp; an array of argument values to pass to the constructor.
...obsolete since jsapi 32 argv jsval * pointer to the element 0 of an array of argument values to pass to the constructor.
TPS Bookmark Lists
each key is the full path for the array of contents specified in the key's value.
...folder contents the contents for a folder are given as an array of objects, representing various bookmark types, described below.
...tags: an array of tags for the bookmark.
Feed content access API
ponents.interfaces.nsifeed); // open a new window var win = window.open("", "feedtest_window"); var doc = win.document.wrappedjsobject; doc.open(); // write the html header and page title doc.write("<html><head><title>feed: " + feed.title.text + "</title></head><body>"); doc.write("<h1>" + feed.title.text + "</h1><p>"); var itemarray = feed.items; var numitems = itemarray.length; // write the article information if (!numitems) { doc.write("<i>no news is good news!</i>"); } else { var i; var theentry; var theurl; var info; for (i=0; i<numitems; i++) { theentry = itemarray.queryelementat(i, components.interfaces.ns...
...we then scan the array of items in the feed by looking at the feed.items nsiarray.
... this array contains nsifeedentry objects that describe each feed item.
Using the Places annotation service
four functions are provided to get this information: getpageannotationinfo(auri, aname, aflags, aexpiration, amimetype, atype) getitemannotationinfo(aitemid, aname, aflags, aexpiration, amimetype, atype) getpageannotationtype(auri, aname); getitemannotationtype(aitemid, aname); the returned type will be one of the value_type constants in mozistoragevaluearray.idl: after bug 377066 the value_type_* type handling was changed to this: type_int32 = 1 type_double = 2 type_string = 3 type_binary = 4 type_int64 = 5 try { var value = annotationservice.getpageannotation(uri, "my_extension/some_annotation"); } catch(e) { // annotation does not exist } other functions getpageswithannotation(aname, resultcount, results); getitemswithannotation...
...c++ callers will want to use getpageswithannotationcomarray which returns a com array, making memory management much easier and reducing the chance of leaks.
...c++ callers will want to use getpageannotationnamestarray which returns a com array, making memory management much easier and reducing the chance of leaks.
Avoiding leaks in JavaScript XPCOM components
to understand closures a little better before examining how they can cause leaks, consider the following example, in which there are two pairs of function objects, and each pair has an instance of the private_data variable: // this function returns an array containing two functions.
... function function_array() { // once this function is done running, this variable is still // accessible to the functions created here.
... var private_data = 0; var result = new array(); result[0] = function() { return (private_data += 1); } result[1] = function() { return (private_data *= 2); } return result; } // this function returns the string "results: 1, 2, 4, 0, 5, 1, 10." function test() { var fns1 = function_array(); var fns2 = function_array(); return "results: " + fns1[0]() + ", " + // increments first private_data to 1 fns1[1]() + ", " + // doubles first private_data to 2 fns1[1]() + ", " + // doubles first private_data to 4 fns2[1]() + ", " + // doubles second private_data to 0 fns1[0]() + ", " + // increments first private_data to 5 fns2[0]() + ", " + // increments second private_data to 1 fns1...
How to build an XPCOM component in JavaScript
}, // [optional] an array of categories to register this component in.
... _xpcom_categories: [{ // each object in the array specifies the parameters to pass to // nsicategorymanager.addcategoryentry().
...finally, you create an array of your components to be created: var components = [helloworld]; and replace nsgetfactory/nsgetmodule to use this array and xpcomutils: if ("generatensgetfactory" in xpcomutils) var nsgetfactory = xpcomutils.generatensgetfactory(components); // firefox 4.0 and higher else var nsgetmodule = xpcomutils.generatensgetmodule(components); // firefox 3.x so the total simplified versio...
Starting WebLock
*/ void undefine(in string prop); /** * returns an array of the keys.
... */ void getkeys(out pruint32 count, [array, size_is(count), retval] out string keys); }; directory service hierarchy there are two steps involved to find directories or files with the directory service (nsidirectoryservice).
...if you need random access to the elements in a nsisimpleenumerator, you can read them from the nsisimpleenumerator, store them in an array, and access them there.
Components.classes
usage in order to retrieve the object for a given contractid, you can query the components.classes array as follows: var clazz0 = components.classes["@mozilla.org/messenger;1"]; clazz0 is the class object for the contractid @mozilla.org/messenger;1, which is not usually used by itself, but whose createinstance and getservice methods can be used to create a new instance of the component or to access the singleton instance, if the contract id represents a service.
... a new xpcom component instance can be created from the returned class object as follows: var obj = components.classes["@mozilla.org/supports-array;1"] .createinstance(components.interfaces.nsisupportsarray); which is a shortcut to var obj = components.classes["@mozilla.org/supports-array;1"] .createinstance(); obj.queryinterface(components.interfaces.nsisupportsarray); if you don't provide a specific interface to createinstance(), it will return an xpconnect wrapper for the component, which only exposes the methods of the nsisupports interface (and under certain circumstances the special wrappedjsobject property).
...erfaces by storing a reference to the object as a constant: const cc = components.classes, ci = components.interfaces; var os = cc["@mozilla.org/observer-service;1"] .getservice(ci.nsiobserverservice); a less known trick, useful when creating multiple instances of the same component, is to use the new operator on the class object: var clazz = components.classes["@mozilla.org/supports-array;1"]; var inst = new clazz(components.interfaces.nsisupportsarray); this implicitly calls the createinstance() method for you.
amIWebInstaller
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) method overview boolean installaddonsfromwebpage(in astring amimetype, in nsidomwindow awindow, in nsiuri areferer, [array, size_is(ainstallcount)] in wstring auris, [array, size_is(ainstallcount)] in wstring ahashes, [array, size_is(ainstallcount)] in wstring anames, [array, size_is(ainstallcount)] in wstring aicons, [optional] in amiinstallcallback acallback, [optional] in pruint32 ainstallcount); boolean isinstallenabled(in astring amimetype, in nsiuri areferer); note: prior to gecko 8.0, all refe...
... methods installaddonsfromwebpage() installs an array of add-ons at the request of a webpage.
... boolean installaddonsfromwebpage( in astring amimetype, in nsidomwindow awindow, in nsiuri areferer, [array, size_is(ainstallcount)] in wstring auris, [array, size_is(ainstallcount)] in wstring ahashes, [array, size_is(ainstallcount)] in wstring anames, [array, size_is(ainstallcount)] in wstring aicons, in amiinstallcallback acallback, optional in pruint32 ainstallcount optional ); parameters amimetype the mimetype for the add-ons.
imgIEncoder
1.0 66 introduced gecko 1.8 inherits from: nsiasyncinputstream last changed in gecko 1.9 (firefox 3) method overview void addimageframe( [array, size_is(length), const] in pruint8 data, in unsigned long length, in pruint32 width, in pruint32 height, in pruint32 stride, in pruint32 frameformat, in astring frameoptions); void encodeclipboardimage(in nsiclipboardimage aclipboardimage, out nsifile aimagefile); obsolete since gecko 1.9 void endimageencode(); void initfromdata([array, size_is(length), const] in pruint8 data, in unsigned long length, in pruint32 width, in pruint32 height, in pruint32 stride, in pruint32 inputformat, in astring outputoptions); voi...
... methods addimageframe() void addimageframe( [array, size_is(length), const] in pruint8 data, in unsigned long length, in pruint32 width, in pruint32 height, in pruint32 stride, in pruint32 frameformat, in astring frameoptions ); parameters data list of bytes in the format specified by inputformat.
...initfromdata() void initfromdata( [array, size_is(length), const] in pruint8 data, in unsigned long length, in pruint32 width, in pruint32 height, in pruint32 stride, in pruint32 inputformat, in astring outputoptions ); parameters data list of bytes in the format specified by inputformat.
mozIAsyncFavicons
icondatacallback acallback); void getfavicondataforpage(in nsiuri apageuri, in nsifavicondatacallback acallback); void setandfetchfaviconforpage(in nsiuri apageuri, in nsiuri afaviconuri, in boolean aforcereload, in unsigned long afaviconloadtype, [optional] in nsifavicondatacallback acallback); void replacefavicondata(in nsiuri afaviconuri, [const,array,size_is(adatalen)] in octet adata, in unsigned long adatalen, in autf8string amimetype, [optional] in prtime aexpiration); void replacefavicondatafromdataurl(in nsiuri afaviconuri, in astring adataurl, [optional] in prtime aexpiration); methods getfaviconurlforpage() retrieve the url of the favicon for the given page.
...however, if no favicon data is currently associated with the favicon uri, adatalen will be 0, adata will be an empty array, and amimetype will be an empty string.
...void replacefavicondata( in nsiuri afaviconuri, [const,array,size_is(adatalen)] in octet adata, in unsigned long adatalen, in autf8string amimetype, [optional] in prtime aexpiration); parameters afaviconuri uri of the favicon whose data is being set.
mozIAsyncHistory
void isurivisited( in nsiuri auri, in mozivisitedstatuscallback acallback ); parameters auri the places for which to retrieve information, identified by either a single place guid, a single uri, or a js array of uris and/or guids.
...this can be a single object, or an array of objects.
... not providing an array or nothing for the visits property of moziplaceinfo.
nsIApplicationUpdateService
6 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void adddownloadlistener(in nsirequestobserver listener); astring downloadupdate(in nsiupdate update, in boolean background); void pausedownload(); void removedownloadlistener(in nsirequestobserver listener); nsiupdate selectupdate([array, size_is(updatecount)] in nsiupdate updates, in unsigned long updatecount); attributes attribute type description backgroundchecker nsiupdatechecker the update checker being used for background update checking.
...nsiupdate selectupdate( [array, size_is(updatecount)] in nsiupdate updates, in unsigned long updatecount ); parameters updates an array of updates that are available to install.
... updatecount the number of updates in the updates array.
nsIBrowserHistory
wstring atitle, in long long alastvisited); obsolete since gecko 15.0 void markpageasfollowedlink(in nsiuri auri); obsolete since gecko 22.0 void markpageastyped(in nsiuri auri); obsolete since gecko 22.0 void registeropenpage(in nsiuri auri); obsolete since gecko 9.0 void removeallpages(); void removepage(in nsiuri auri); void removepages([array, size_is(alength)] in nsiuri auris, in unsigned long alength, in boolean adobatchnotify); void removepagesbytimeframe(in long long abegintime, in long long aendtime); void removepagesfromhost(in autf8string ahost, in boolean aentiredomain); void removevisitsbytimeframe(in long long abegintime, in long long aendtime); void unregisteropenpage(in nsiuri auri); ...
... void removepages( [array, size_is(alength)] in nsiuri auris, in unsigned long alength, in boolean adobatchnotify /* parameter removed in gecko 9.0 */ ); parameters auris an array of page uris to be removed from history.
... alength the number of pages listed in the auris array.
nsICRLManager
inherits from: nsisupports last changed in gecko 1.7 method overview wstring computenextautoupdatetime(in nsicrlinfo info, in unsigned long autoupdatetype, in double noofdays); void deletecrl(in unsigned long crlindex); nsiarray getcrls(); void importcrl([array, size_is(length)] in octet data, in unsigned long length, in nsiuri uri, in unsigned long type, in boolean dosilentdownload, in wstring crlkey); void reschedulecrlautoupdate(); boolean updatecrlfromurl(in wstring url, in wstring key); constants constant value description type_autoupdate_time_based 1 type_autoupdate_freq_based 2 methods computenextautoupdatetime() wstring computenextautoupdatetime( ...
...nsiarray getcrls(); parameters none.
...void importcrl( [array, size_is(length)] in octet data, in unsigned long length, in nsiuri uri, in unsigned long type, in boolean dosilentdownload, in wstring crlkey ); parameters data length uri type dosilentdownload crlkey reschedulecrlautoupdate() this would reschedule the autoupdate of crls with auto update enable.
nsIClipboard
inherits from: nsisupports last changed in gecko 30.0 (firefox 30.0 / thunderbird 30.0 / seamonkey 2.27) method overview void emptyclipboard(in long awhichclipboard); void forcedatatoclipboard(in long awhichclipboard); obsolete since gecko 1.8 void getdata(in nsitransferable atransferable, in long awhichclipboard); boolean hasdatamatchingflavors([array, size_is(alength)] in string aflavorlist, in unsigned long alength, in long awhichclipboard); void setdata(in nsitransferable atransferable, in nsiclipboardowner anowner, in long awhichclipboard); boolean supportsselectionclipboard(); boolean supportsfindclipboard(); constants most clipboard operations in firefox use kglobalclipboard, which is the one also used ...
... boolean hasdatamatchingflavors( [array, size_is(alength)] in string aflavorlist, in unsigned long alength, in long awhichclipboard ); parameters aflavorlist an array of ascii strings.
... see also nsiclipboardowner nsitransferable nsiarray using the clipboard ...
nsICommandLineRunner
last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsicommandline method overview void init(in long argc, in nscharptrarray argv, in nsifile workingdir, in unsigned long state); void run(); void setwindowcontext(in nsidomwindow awindow); attributes attribute type description helptext autf8string process and combine the help text provided by each command-line handler.
...void init( in long argc, in nscharptrarray argv, in nsifile workingdir, in unsigned long state ); parameters argc the number of arguments being passed.
... argv an array storing pointers to the arguments workingdir directory where the command will run.
nsIContentSniffer
method overview acstring getmimetypefromcontent(in nsirequest arequest, [const,array,size_is(alength)] in octet adata, in unsigned long alength); methods getmimetypefromcontent() given a chunk of data, determines a mime type.
...acstring getmimetypefromcontent( in nsirequest arequest, [const,array,size_is(alength)] in octet adata, in unsigned long alength ); parameters arequest the request where this data came from.
...tcomplexvalue("intl.charset.default", ci.nsipreflocalizedstring).data; } catch (e) { } let conv = cc["@mozilla.org/intl/scriptableunicodeconverter"] .createinstance(ci.nsiscriptableunicodeconverter); conv.charset = charset; try { let str = conv.convertfrombytearray(adata, alength); if (str.substring(0, 5) == "%pdf-") return "application/pdf"; // we detected a pdf file } catch (e) { // try to get information from arequest } ...
nsIEditorMailSupport
inherits from: nsisupports last changed in gecko 1.7 method overview nsisupportsarray getembeddedobjects(); nsidomnode insertascitedquotation(in astring aquotedtext, in astring acitation, in boolean ainserthtml); nsidomnode insertasquotation(in astring aquotedtext); void inserttextwithquotations(in domstring astringtoinsert); void pasteascitedquotation(in astring acitation, in long aselectiontype); void pasteasquotation(in long aselectiontype); void rewrap(in boolean arespectnewlines); void stripcites(); methods getembeddedobjects() get a list of img and object tags in the current document.
... nsisupportsarray getembeddedobjects(); parameters none.
... return value an nsisupportsarray containing the img and object tags of the current document.
nsIEditorSpellCheck
ance(components.interfaces.nsieditorspellcheck); method overview void addwordtodictionary(in wstring word); boolean canspellcheck(); void checkcurrentdictionary(); boolean checkcurrentword(in wstring suggestedword); boolean checkcurrentwordnosuggest(in wstring suggestedword); astring getcurrentdictionary(); void getdictionarylist([array, size_is(count)] out wstring dictionarylist, out pruint32 count); wstring getnextmisspelledword(); void getpersonaldictionary(); wstring getpersonaldictionaryword(); wstring getsuggestedword(); void ignorewordalloccurrences(in wstring word); void initspellchecker(in nsieditor editor, in boolean enableselectionchecking); void removewor...
...void getdictionarylist( [array, size_is(count)] out wstring dictionarylist, out pruint32 count ); parameters dictionarylist an array into which the list of dictionary name strings are placed.
... count on return, contains the number of entries in the dictionarylist array.
nsIFaviconDataCallback
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void oncomplete(in nsiuri auri, in unsigned long adatalen, [const,array,size_is(adatalen)] in octet adata, in autf8string amimetype); methods oncomplete() called when the required favicon's information is available.
...void oncomplete( in nsiuri auri, in unsigned long adatalen, [const,array,size_is(adatalen)] in octet adata, in autf8string amimetype ); parameters auri receives the "favicon uri" (not the "favicon link uri") associated to the requested page.
... adata icon data, or an empty array if adatalen is 0.
nsIHTMLEditor
ntstate(out boolean acanindent, out boolean acanoutdent); void getinlineproperty(in nsiatom aproperty, in astring aattribute, in astring avalue, out boolean afirst, out boolean aany, out boolean aall); astring getinlinepropertywithattrvalue(in nsiatom aproperty, in astring aattribute, in astring avalue, out boolean afirst, out boolean aany, out boolean aall); nsisupportsarray getlinkedobjects(); void getlistitemstate(out boolean amixed, out boolean ali, out boolean adt, out boolean add); void getliststate(out boolean amixed, out boolean aol, out boolean aul, out boolean adl); astring getparagraphstate(out boolean amixed); nsidomelement getselectedelement(in astring atagname); nsidomelement getselectioncontainer(); ...
...nsiatom aproperty, in astring aattribute, in astring avalue, out boolean afirst, out boolean aany, out boolean aall ); parameters aproperty aattribute avalue afirst aany aall return value getlinkedobjects() find all the nodes in the document which contain references to outside uris (for example a href, img src, script src, and so on.) the objects in the array will be type nsiurirefobject.
... nsisupportsarray getlinkedobjects(); parameters none.
nsILoginManagerPrompter
this service, use: var loginmanagerprompter = components.classes["@mozilla.org/login-manager/prompter;1"] .getservice(components.interfaces.nsiloginmanagerprompter); method overview void init(in nsidomwindow awindow); void prompttochangepassword(in nsilogininfo aoldlogin, in nsilogininfo anewlogin); void prompttochangepasswordwithusernames([array, size_is(count)] in nsilogininfo logins, in pruint32 count, in nsilogininfo anewlogin); void prompttosavepassword(in nsilogininfo alogin); methods init() initialize the prompter.
... void prompttochangepasswordwithusernames( [array, size_is(count)] in nsilogininfo logins, in pruint32 count, in nsilogininfo anewlogin ); parameters logins an array of existing logins.
... count (length of the array) anewlogin the new login.
nsISocketTransportService
nsisockettransport createtransport(in array<acstring> asockettypes, in autf8string ahost, in long aport, in nsiproxyinfo aproxyinfo); void init(); obsolete since gecko 1.8 void notifywhencanattachsocket(in nsirunnable aevent); native code only!
... nsisockettransport createtransport( in array<acstring> asockettypes, in autf8string ahost, in long aport, in nsiproxyinfo aproxyinfo ); parameters asockettypes array of socket type strings.
...pass an empty array [] if the default socket type should be used.
nsITransferable
method overview void adddataflavor( in string adataflavor ); nsisupportsarray flavorstransferablecanexport( ); nsisupportsarray flavorstransferablecanimport( ); void getanytransferdata( out string aflavor, out nsisupports adata, out unsigned long adatalen ); void gettransferdata( in string aflavor, out nsisupports adata, out unsigned long adatalen ); void init(in nsiloadcontext acontext); boolean islargedataset( ); voi...
... nsisupportsarray flavorstransferablecanexport(); parameters none.
... nsisupportsarray flavorstransferablecanimport(); parameters none.
nsIWifiListener
1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) method overview void onchange([array, size_is(alen)] in nsiwifiaccesspoint accesspoints, in unsigned long alen); void onerror(in long error); methods onchange() called when the list of available access points changes.
... void onchange( [array, size_is(alen)] in nsiwifiaccesspoint accesspoints, in unsigned long alen ); parameters accesspoints an array of nsiwifiaccesspoint objects representing all currently-available wifi access points.
... alen the number of entries in the accesspoints array.
nsIXPConnect
void debugdumpevalinjsstackframe(in pruint32 aframenumber, in string asourcetext); void debugdumpjsstack(in prbool showargs, in prbool showlocals, in prbool showthisprops); void debugdumpobject(in nsisupports acomobj, in short depth); [noscript,notxpcom] prbool definedomquickstubs(in jscontextptr cx, in jsobjectptr proto, in pruint32 flags, in pruint32 interfacecount, [array, size_is(interfacecount)] in nsiidptr interfacearray); jsval evalinsandboxobject(in astring source, in jscontextptr cx, in nsixpconnectjsobjectholder sandbox, in prbool returnstringonly); native code only!
... [noscript,notxpcom] prbool definedomquickstubs( in jscontextptr cx, in jsobjectptr proto, in pruint32 flags, in pruint32 interfacecount, [array, size_is(interfacecount)] in nsiidptr interfacearray ); parameters cx a context.
... interfacearray the interfaces the class implements; interfacearray and interfacecount are like what nsiclassinfo.getinterfaces returns.
nsIXULTemplateQueryProcessor
result aleft, in nsixultemplateresult aright, in nsiatom avar, in unsigned long asorthints); nsisupports compilequery(in nsixultemplatebuilder abuilder, in nsidomnode aquery, in nsiatom arefvariable, in nsiatom amembervariable); void done(); nsisimpleenumerator generateresults(in nsisupports adatasource, in nsixultemplateresult aref, in nsisupports aquery); nsisupports getdatasource(in nsiarray adatasources, in nsidomnode arootnode, in boolean aistrusted, in nsixultemplatebuilder abuilder, out boolean ashoulddelaybuilding); void initializeforbuilding(in nsisupports adatasource, in nsixultemplatebuilder abuilder, in nsidomnode arootnode); nsixultemplateresult translateref(in nsisupports adatasource, in astring arefstring); methods addbinding() add a variable binding for a particul...
...this list is processed by the builder and supplied to the query processor in the adatasources array as a list of nsiuri objects or nsidomnode objects.
...nsisupports getdatasource( in nsiarray adatasources, in nsidomnode arootnode, in boolean aistrusted, in nsixultemplatebuilder abuilder, out boolean ashoulddelaybuilding ); parameters adatasources the list of nsiuri objects and/or nsidomnode objects.
Xray vision
xray semantics for object and array the exceptions are object and array: their interesting state is in javascript, not c++.
...so the semantics defined for object and array xrays aim to make it easy for privileged code to treat untrusted objects like simple dictionaries.
... there are two main sorts of restrictions: first, the chrome code might expect to rely on the prototype's integrity, so the object's prototype is protected: the xray has the standard object or array prototype, without any modifications that content may have done to that prototype.
Folders and message lists
gfolderdisplay.selectedmessages: returns an array of nsimsgdbhdrs for the selected messages.
... gfolderdisplay.selectedmessageuris: returns an array of the uris corresponding to the selected messages.
... gfolderdisplay.selectmessages(arrayofmsghdrs): selects all the messages in the array arrayofmsghdrs.
Working with windows in chrome code
here is helper function that will package the data correctly and pass it to the newly opened window: function opendialog(parentwindow, url, windowname, features) { var array = components.classes["@mozilla.org/array;1"] .createinstance(components.interfaces.nsimutablearray); for (var i = 4; i < arguments.length; i++) { var variant = components.classes["@mozilla.org/variant;1"] .createinstance(components.interfaces.nsiwritablevariant); variant.setfromvariant(arguments[i]); array.appen...
...delement(variant, false); } var watcher = components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getservice(components.interfaces.nsiwindowwatcher); return watcher.openwindow(parentwindow, url, windowname, features, array); } the function almost works the same as window.opendialog but accepts an optional parent window as first parameter.
...the only data types that can be passed to the new window are primitives and arrays.
FunctionType
argtypes ctype[] a sealed array of the argument types.
...for other function, pointer, and array types, this should be a valid c type expression.
... method overview methods inherited from ctype ctype array([n]) string tosource() string tostring() functiontype cdata functiontype cdata cannot be constructed.
PointerType
for other function, pointer, and array types, this should be a valid c type expression.
... method overview methods inherited from ctype ctype array([n]) string tosource() string tostring() pointertype cdata syntax cdata pointertype(); pointertype is pointertype ctype.
... note: this is never ctypes.void_t or an array type with an unspecified length.
ctypes
method overview ctype arraytype(type[, length]); cdata cast(data, type); ctype functiontype(abi, returntype[, argtype1, ...]); cdata int64(n); string libraryname(name); library open(libspec); ctype pointertype(typespec); ctype structtype(name[, fields]); cdata uint64(n); properties property type description errno number the value of the latest system error.
... for example, ctypes.char.array(30)(str) converts the string str to utf-8 and returns a new cdata object of array type.
...rved3': ctypes.unsigned_char}, {'breserved4': ctypes.unsigned_char}, {'breserved5': ctypes.unsigned_char}, {'breserved6': ctypes.unsigned_char}, {'dwdata': ctypes.uintptr_t}, {'istring': ctypes.intptr_t} ]); } else { throw new error("wut?!"); } console.log(struct_tbbutton.size); // 20 on 32-bit, 32 on 64-bit if i'm not mistaken there is another way to do this, we can use arraytype, but example for this i don't know at this time.
Debugger.Memory - Firefox Developer Tools
it has the following properties: collections the collections property’s value is an array.
...for each collection slice that occurred, there is an entry in the collections array with the following form: { "starttimestamp":timestamp, "endtimestamp":timestamp, } here the timestamp values are timestamps of the gc slice’s start and end events.
... array objects may also be optimized, if the set of live indices is dense.
Monster example - Firefox Developer Tools
specifically: the code creates an object with three properties, each an array: one for fierce monsters one for friendly monsters one for monsters who haven't decided yet.
... for each array, the code creates and appends 5000 randomly-initialized monsters.
... so the structure of the memory allocated on the javascript heap is an object containing three arrays, each containing 5000 objects (monsters), each object containing a string and two integers: ...
Rich output - Firefox Developer Tools
in particular, it: provides extra information for certain types enables detailed examination of the object's properties provides richer information for dom elements, and enables you to select them in the inspector type-specific rich output the web console provides rich output for many object types, including the following: object array date promise regexp window document element event examining object properties when an object is logged to the console it has a right-pointing triangle next to it, indicating that it can be expanded.
...the output will look something like this: console.log(todolist) array(4) [ {…}, {…}, {…}, {…} ] debugger eval code:1:9 undefined if you expand objects, such as arrays, you get slightly different content.
... for example, by expanding the array in the above list, i get the following: console.log(todolist) (4) […] ​ 0: object { status: "done", description: "morning pages", datecreated: 1552404478137 } ​ 1: object { status: "in progress", description: "refactor styles", datecreated: 1552404493169 } ​ 2: object { status: "to do", description: "create feedback form", datecreated: 1552404512630 } ​ 3: object { status: "to do", description: "normalize table", datecreated: 1552404533790 } ​ length: 4 ​ <prototype>: array [] debugger eval code:1:9 undefined highlighting and inspecting dom nodes if you hover the mouse over any dom element in the console output, it's highlighted on the page: in the screenshot above you'll also see a blue "target" icon next to the node in the console output:...
AnalyserNode.frequencyBinCount - Web APIs
syntax var arraylength = analysernode.frequencybincount; value an unsigned integer, equal to the number of values that analysernode.getbytefrequencydata() and analysernode.getfloatfrequencydata() copy into the provided typedarray.
... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5 - 1; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { bar...
...height = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,barwidth,barheight/2); x += barwidth; } }; draw(); specifications specification status comment web audio apithe definition of 'frequencybincount' in that specification.
AudioBuffer.copyFromChannel() - Web APIs
the copyfromchannel() method of the audiobuffer interface copies the audio sample data from the specified channel of the audiobuffer to a specified float32array.
... syntax myarraybuffer.copyfromchannel(destination, channelnumber, startinchannel); parameters destination a float32array to copy the channel's samples to.
... var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var anotherarray = new float32array(length); myarraybuffer.copyfromchannel(anotherarray, 1, 0); specification specification status comment web audio apithe definition of 'copyfromchannel' in that specification.
AudioContext.createMediaStreamDestination() - Web APIs
stopping the mediarecorder causes the dataavailable event to fire, and the event data is pushed into the chunks array.
... after that, the stop event fires, a new blob is made of type opus — which contains the data in the chunks array, and a new window (tab) is then opened that points to a url created from the blob.
... function(e) { if (!clicked) { mediarecorder.start(); osc.start(0); e.target.innerhtml = "stop recording"; clicked = true; } else { mediarecorder.stop(); osc.stop(0); e.target.disabled = true; } }); mediarecorder.ondataavailable = function(evt) { // push each chunk (blobs) in an array chunks.push(evt.data); }; mediarecorder.onstop = function(evt) { // make blob out of our blobs, and open it.
AudioTrack - Web APIs
usage notes to get an audiotrack for a given media element, use the element's audiotracks property, which returns an audiotracklist object from which you can get the individual tracks contained in the media: var el = document.queryselector("video"); var tracks = el.audiotracks; you can then access the media's individual tracks using either array syntax or functions such as foreach().
... example this example returns an array of track kinds and labels for potential use in a user interface to select audio tracks for a specified media element.
...acklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "main-desc", "translation", "commentary" ]; el.audiotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); return tracklist; } the resulting tracklist contains an array of audio tracks whose kind is one of those in the array wantedkinds, with each entry providing the track's id, kind, and label.
AudioWorkletNode() - Web APIs
outputchannelcount optional an array defining the number of channels for each output.
...the array length must match numberofoutputs.
... indexsizeerror the length of options.outputchannelcount array does not match options.numberofoutputs.
AudioWorkletProcessor - Web APIs
this method gets called for each block of 128 sample-frames and takes input and output arrays and calculated values of custom audioparams (if they are defined) as parameters.
... you can use inputs and audio parameter values to fill the outputs array, which by default holds silence.
...the array of audioparamdescriptor-based objects returned is used internally to create the audioparams during the instantiation of the audioworkletnode.
AuthenticatorAssertionResponse.authenticatorData - Web APIs
the authenticatordata property of the authenticatorassertionresponse interface returns an arraybuffer containing information from the authenticator such as the relying party id hash (rpidhash), a signature counter, test of user presence, user verification flags, and any extensions processed by the authenticator.
... syntax var authnrdata = authenticatorassertionresponse.authenticatordata; value an arraybuffer that has a arraybuffer.bytelength of at least 37 bytes, containing the following fields: rpidhash (32 bytes) - a sha256 hash of the relying party id that was seen by the browser.
... examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionpkcred) { var authenticatordata = assertionpkcred.response.authenticatordata; // maybe try to convert the authenticatordata to see what's inside // send response and client extensions to the server so that it can //...
AuthenticatorAssertionResponse.signature - Web APIs
the signature read-only property of the authenticatorassertionresponse interface is an arraybuffer object which is the signature of the authenticator for both authenticatorassertionresponse.authenticatordata and a sha-256 hash of the client data (authenticatorassertionresponse.clientdatajson).
... syntax signature = authenticatorassertionresponse.signature value an arraybuffer object which the signature of the authenticator (using its private key) for both authenticatorassertionresponse.authenticatordata and a sha-256 hash given by the client for its data (the challenge, the origin, etc.
... examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionpkcred) { var signature = assertionpkcred.response.signature; // send response and client extensions to the server so that it can // go on with the authentication }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'signature' in that specification.
AuthenticatorAssertionResponse.userHandle - Web APIs
the userhandle read-only property of the authenticatorassertionresponse interface is an arraybuffer object which is an opaque identifier for the given user.
... syntax userhandle = authenticatorassertionresponse.userhandle value an arraybuffer object which is an opaque identifier for the current user.
...username, e-mail, phone number, etc.) examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionpkcred) { var userhandle = assertionpkcred.response.userhandle; // send response and client extensions to the server so that it can // go on with the authentication }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'userhandle' in that specification.
AuthenticatorAssertionResponse - Web APIs
authenticatorassertionresponse.authenticatordata secure contextread only an arraybuffer containing information from the authenticator such as the relying party id hash (rpidhash), a signature counter, test of user presence and user verification flags, and any extensions processed by the authenticator.
... authenticatorassertionresponse.userhandle secure contextread only an arraybuffer containing an opaque user identifier.
... examples var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { var assertionresponse = credentialinfoassertion.response; // do something specific with the response // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'authenticatorassertionresponse interface' in that specification.
AuthenticatorAttestationResponse.attestationObject - Web APIs
the attestationobject property of the authenticatorattestationresponse interface returns an arraybuffer containing the new public key, as well as signature over the entire attestationobject with a private key that is stored in the authenticator when it is manufactured.
... syntax attestobj = authenticatorattestationresponse.attestationobject properties after decoding the cbor encoded arraybuffer, the resulting javascript object will contain the following properties: authdata the same as authenticatorassertionresponse.authenticatordata.
... examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var attestationobj = newcredentialinfo.response.attestationobject; // this will be a cbor encoded arraybuffer // do something with the response // (s...
Blob() - Web APIs
WebAPIBlobBlob
the content of the blob consists of the concatenation of the values given in the parameter array.
... syntax var newblob = new blob(array, options); parameters array an array of arraybuffer, arraybufferview, blob, usvstring objects, or a mix of any of such objects, that will be put inside the blob.
... example var afileparts = ['<a id="a"><b id="b">hey!</b></a>']; // an array consisting of a single domstring var omyblob = new blob(afileparts, {type : 'text/html'}); // the blob specification specification status comment file apithe definition of 'blob()' in that specification.
BlobBuilder - Web APIs
method overview void append(in arraybuffer data); void append(in blob data); void append(in string data, [optional] in string endings); blob getblob([optional] in domstring contenttype); file getfile(in domstring name, [optional] in domstring contenttype); methods append() appends the contents of the specified javascript object to the blob being built.
... if the value you specify isn't a blob, arraybuffer, or string, the value is coerced to a string before being appended to the blob.
... void append( in arraybuffer data ); void append( in blob data ); void append( in string data, [optional] in string endings ); parameters data the data to append to the blob being constructed.
Bluetooth.requestDevice() - Web APIs
the available options are: filters[]: an array of bluetoothscanfilters.
... this filter consists of an array of bluetoothserviceuuids, a name parameter, and a nameprefix parameter.
... optionalservices[]: an array of bluetoothserviceuuids.
BluetoothRemoteGATTCharacteristic - Web APIs
bluetoothremotegattcharacteristic.getdescriptors() returns a promise that resolves to an array of all bluetoothgattdescriptor objects for a given descriptor uuid.
... bluetoothremotegattcharacteristic.readvalue() returns a promise that resolves to an arraybuffer holding a duplicate of the value property if it is available and supported.
... bluetoothremotegattcharacteristic.writevalue() sets the value property to the bytes contained in an arraybuffer and returns a promise.
writeValue() - Web APIs
the bluetoothremotegattdescriptor.writevalue() method sets the value property to the bytes contained in an arraybuffer and returns a promise.
... syntax bluetoothremotegattdescriptor.writevalue(array[]).then(function() { ...
... }) parameters array sets the value with the bytes contained in the array.
CSSStyleSheet.insertRule() - Web APIs
* note that an array is needed for declarations and rules since ecmascript does * not guarantee a predictable object iteration order, and since css is * order-dependent.
... * @param {array} rules accepts an array of json-encoded declarations * @example addstylesheetrules([ ['h2', // also accepts a second argument as an array of arrays instead ['color', 'red'], ['background-color', 'green', true] // 'true' for !important rules ], ['.myclass', ['background-color', 'yellow'] ] ]); */ function addstylesheetrules (rules) { var styleel = document.createelement('style'); // append <style> element to <head> document.head.appendchild(styleel); // grab style element's sheet var stylesheet = styleel.sheet; for (var i = 0; i < rules.length; i++) { var j = 1, rule = rules[i], selector = rule[0], propstr = ''; // if the second argument of a rule is an array of arrays, correct our variables.
... if (array.isarray(rule[1][0])) { rule = rule[1]; j = 0; } for (var pl = rule.length; j < pl; j++) { var prop = rule[j]; propstr += prop[0] + ': ' + prop[1] + (prop[2] ?
CSSUnparsedValue - Web APIs
methods cssunparsedvalue.entries() returns an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
... cssunparsedvalue.keys() returns a new array iterator object that contains the keys for each index in the cssunparsedvalue object.
... cssunparsedvalue.values() returns a new array iterator object that contains the values for each index in the cssunparsedvalue object.
Using the CSS Painting API - Web APIs
to be able to access properties, we include the static inputproperties() method, which provides live access to css properties, including regular properties and custom properties, and returns an array of property names.
... registerpaint('boxbg', class { static get contextoptions() { return {alpha: true}; } /* use this function to retrieve any custom properties (or regular properties, such as 'height') defined for the element, return them in the specified array */ static get inputproperties() { return ['--boxcolor', '--widthsubtractor']; } paint(ctx, size, props) { /* ctx -> drawing context size -> paintsize: width and height props -> properties: get() method */ ctx.fillstyle = props.get('--boxcolor'); ctx.fillrect(0, size.height/3, size.width*0.4 - props.get('--widthsubtractor'), size.height*0.6); } }); w...
...the first element in the returned array will be a cssunparsedvalue.
CSS Typed Object Model API - Web APIs
cssstylevalue.parseall() the parseall() method of the cssstylevalue interface sets all occurences of a specific css property to the specified valueand returns an array of cssstylevalue objects, each containing one of the supplied values.
... cssunparsedvalue.entries() method returning an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
... cssunparsedvalue.keys() method returning a new array iterator object that contains the keys for each index in the array.
Cache - Web APIs
WebAPICache
cache.matchall(request, options) returns a promise that resolves to an array of all matching requests in the cache object.
... cache.addall(requests) takes an array of urls, retrieves them, and adds the resulting response objects to the given cache.
... cache.keys(request, options) returns a promise that resolves to an array of cache keys.
CanvasRenderingContext2D.createImageData() - Web APIs
each pixel within an imagedata object consists of four array values, so the object's data property has a length of 4 × 5,000, or 20,000.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const imagedata = ctx.createimagedata(100, 50); console.log(imagedata); // imagedata { width: 100, height: 50, data: uint8clampedarray[20000] } filling a blank imagedata object this example creates and fills a new imagedata object with purple pixels.
...the array values associated with each pixel are r (red), g (green), b (blue), and a (alpha), in that order.
DOMTokenList.forEach() - Web APIs
syntax tokenlist.foreach(callback [, thisarg]); parameters callback function to execute for each element, eventually taking three arguments: currentvalue the current element being processed in the array.
... currentindex the index of the current element being processed in the array.
... listobj the array that foreach() is being applied to.
DedicatedWorkerGlobalScope.postMessage() - Web APIs
transferlist optional an optional array of transferable objects to transfer ownership of.
... only messageport and arraybuffer objects can be transferred.
...as seen above, if you want to pass multiple values you can send an array.
Document.getAnimations() - Web APIs
the getanimations() method of the document interface returns an array of all animation objects currently in effect whose target elements are descendants of the document.
... this array includes css animations, css transitions, and web animations.
... return value an array of animation objects, each representing one animation currently associated with elements which are descendants of the document on which it's called.
Document.getElementsByClassName() - Web APIs
the getelementsbyclassname method of document interface returns an array-like object of all child elements which have all of the given class name(s).
... the 'red' and 'test' classes: document.getelementsbyclassname('red test') get all elements that have a class of 'test', inside of an element that has the id of 'main': document.getelementbyid('main').getelementsbyclassname('test') get the first element with a class of 'test', or undefined if there is no matching element: document.getelementsbyclassname('test')[0] we can also use methods of array.prototype on any htmlcollection by passing the htmlcollection as the method's this value.
... here we'll find all div elements that have a class of 'test': var testelements = document.getelementsbyclassname('test'); var testdivs = array.prototype.filter.call(testelements, function(testelement){ return testelement.nodename === 'div'; }); get the first element whose class is 'test' this is the most commonly used method of operation.
Document.querySelectorAll() - Web APIs
; here, an attribute selector is used to return a list of the list items contained within a list whose id is userlist which have a data-active attribute whose value is 1: var container = document.queryselector("#userlist"); var matches = container.queryselectorall("li[data-active='1']"); accessing the matches once the nodelist of matching elements is returned, you can examine it just like any array.
... if the array is empty (that is, its length property is 0), then no matches were found.
... otherwise, you can simply use standard array notation to access the contents of the list.
Element.getAnimations() - Web APIs
the getanimations() method of the element interface (specified on the animatable mixin) returns an array of all animation objects affecting this element or which are scheduled to do so in future.
... note: this array includes css animations, css transitions, and web animations.
... return value an array of animation objects, each representing an animation currently targetting the element on which this method is called, or one of its descendant elements if { subtree: true } is specified.
Element.getAttributeNames() - Web APIs
the getattributenames() method of the element interface returns the attribute names of the element as an array of strings.
... if the element has no attributes it returns an empty array.
...ributenames(); example // iterate over element's attributes for (let name of element.getattributenames()) { let value = element.getattribute(name); console.log(name, value); } polyfill if (element.prototype.getattributenames == undefined) { element.prototype.getattributenames = function () { var attributes = this.attributes; var length = attributes.length; var result = new array(length); for (var i = 0; i < length; i++) { result[i] = attributes[i].name; } return result; }; } specifications specification status comment domthe definition of 'element.getattributenames' in that specification.
Event.composedPath() - Web APIs
the composedpath() method of the event interface returns the event’s path which is an array of the objects on which listeners will be invoked.
... return value an array of eventtarget objects representing the objects on which an event listener will be invoked.
...the <open-shadow> element's composed path is this: array [ p, shadowroot, open-shadow, body, html, htmldocument https://mdn.github.io/web-components-examples/composed-composed-path/, window ] whereas the <closed-shadow> element's composed path is a follows: array [ closed-shadow, body, html, htmldocument https://mdn.github.io/web-components-examples/composed-composed-path/, window ] in the second case, the event listeners only propagate as far as th...
FileReaderSync - Web APIs
methods filereadersync.readasarraybuffer() this method converts a specified blob or a file into an arraybuffer representing the input data as a binary string.
...this method is deprecated, consider using readasarraybuffer() instead.
... yeschrome android full support yesfirefox android full support 8opera android full support yessafari ios full support yessamsung internet android full support yesreadasarraybufferchrome full support yesedge full support 12firefox full support 8ie full support yesopera full support yessafari full support ...
Gamepad.axes - Web APIs
WebAPIGamepadaxes
the gamepad.axes property of the gamepad interface returns an array representing the controls with axes present on the device (e.g.
... analog thumb sticks).- each entry in the array is a floating point value in the range -1.0 – 1.0, representing the axis position from the lowest value (-1.0) to the highest value (1.0).
...gator.webkitgetgamepads()[0]; } else { var gp = navigator.getgamepads()[0]; } if(gp.axes[0] != 0) { b -= gp.axes[0]; } else if(gp.axes[1] != 0) { a += gp.axes[1]; } else if(gp.axes[2] != 0) { b += gp.axes[2]; } else if(gp.axes[3] != 0) { a -= gp.axes[3]; } ball.style.left = a*2 + "px"; ball.style.top = b*2 + "px"; var start = raf(gameloop); }; value an array of double values.
GamepadButton - Web APIs
a gamepadbutton object is returned by querying any value of the array returned by the buttons property of the gamepad interface.
... note: this is the case in firefox gecko 28 and later; chrome and earlier firefox versions still return an array of double values when this property is accessed.
... example the following code is taken from my gamepad api button demo (you can view the demo live, and find the source code on github.) note the code fork — in chrome navigator.getgamepads needs a webkit prefix and the button values are stored as an array of double values, whereas in firefox navigator.getgamepads doesn't need a prefix, and the button values are stored as an array of gamepadbutton objects; it is the gamepadbutton.value or gamepadbutton.pressed properties of these we need to access, depending on what type of buttons they are.
HTMLInputElement.webkitEntries - Web APIs
the read-only webkitentries property of the htmlinputelement interface contains an array of file system entries (as objects based on filesystementry) representing files and/or directories selected by the user using an <input> element of type file, but only if that selection was made using drag-and-drop: selecting a file in the dialog will leave the property empty (bug 1326031).
... the array can only contain directories if the webkitdirectory property is true.
... syntax var entries = htmlinputelement.webkitentries; value an array of objects based on filesystementry, each representing one file which is selected in the <input> element.
Headers - Web APIs
WebAPIHeaders
headers.foreach() executes a provided function once for each array element.
... obsolete methods headers.getall() used to return an array of all the values of a header within a headers object with a given name; this method has now been deleted from the spec, and headers.get() now returns all values of a given name instead of just the first one.
... examples in the following snippet, we create a new header using the headers() constructor, add a new header to it using append(), then return that header value using get(): var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.get('content-type') // should return 'text/xml' the same can be achieved by passing an array of arrays or an object literal to the constructor: var myheaders = new headers({ 'content-type': 'text/xml' }); // or, using an array of arrays: myheaders = new headers([ ['content-type', 'text/xml'] ]); myheaders.get('content-type') // should return 'text/xml' specifications specification status comment fetchthe definition of 'headers' in that specification.
Ajax navigation example - Web APIs
"</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>this paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p> <div id="ajax-content"> <?php } ?> <p>this is the content of <strong>first_page.php</strong>.</p> <?php if ($as_json) { echo json_encode(array("page" => $page_title, "content" => ob_get_clean())); } else { ?> </div> <p>this paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p> <?php include "include/after_content.php"; echo "</body>\n</html>"; } ?> second_page.php: <?php $page_title = "second page"; $as_json = false; if (isset($_get["view_as"]) && $_get["...
..."</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>this paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p> <div id="ajax-content"> <?php } ?> <p>this is the content of <strong>second_page.php</strong>.</p> <?php if ($as_json) { echo json_encode(array("page" => $page_title, "content" => ob_get_clean())); } else { ?> </div> <p>this paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p> <?php include "include/after_content.php"; echo "</body>\n</html>"; } ?> third_page.php: <?php $page_title = "third page"; $page_content = "<p>this is the content of <strong>third_page.
...this content is stored into a php variable.</p>"; if (isset($_get["view_as"]) && $_get["view_as"] == "json") { echo json_encode(array("page" => $page_title, "content" => $page_content)); } else { ?> <!doctype html> <html> <head> <?php include "include/header.php"; echo "<title>" .
IDBIndex.multiEntry - Web APIs
the multientry read-only property of the idbindex interface returns a boolean value that affects how the index behaves when the result of evaluating the index's key path yields an array.
... syntax var ismultientry = myindex.multientry; value a boolean: value effect true there is one record in the index for each item in an array of keys.
... false there is one record for each key that is an array.
IDBIndex - Web APIs
WebAPIIDBIndex
idbindex.multientry read only affects how the index behaves when the result of evaluating the index's key path yields an array.
... if true, there is one record in the index for each item in an array of keys.
... if false, then there is one record for each key that is an array.
IDBObjectStore.createIndex() - Web APIs
note that it is possible to create an index with an empty keypath, and also to pass in a sequence (array) as a keypath.
... multientry if true, the index will add an entry in the index for each array element when the keypath resolves to an array.
... if false, it will add one single entry containing the array.
ImageData - Web APIs
WebAPIImageData
constructors imagedata() creates an imagedata object from a given uint8clampedarray and the size of the image it contains.
... if no array is given, it creates an image of a transparent black rectangle.
... properties imagedata.data read only is a uint8clampedarray representing a one-dimensional array containing the data in the rgba order, with integer values between 0 and 255 (inclusive).
IntersectionObserver.IntersectionObserver() - Web APIs
if the threshold list is empty, it's set to the array [0.0].
...the callback receives as input two parameters: entries an array of intersectionobserverentry objects, each representing one threshold which was crossed, either becoming more or less visible than the percentage specified by that threshold.
... threshold either a single number or an array of numbers between 0.0 and 1.0, specifying a ratio of intersection area to total bounding box area for the observed target.
KeyboardLayoutMap - Web APIs
properties keyboardlayoutmap.entries read only returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
... keyboardlayoutmap.keys read only returns a new array iterator object that contains the keys for each index in the array.
... keyboardlayoutmap.values read only returns a new array iterator object that contains the values for each index in the keyboardlayoutmap object.
MediaDevices.enumerateDevices() - Web APIs
the returned promise is resolved with a mediadeviceinfo array describing the devices.
... syntax var enumeratorpromise = navigator.mediadevices.enumeratedevices(); return value a promise that receives an array of mediadeviceinfo objects when the promise is fulfilled.
... each object in the array describes one of the available media input and output devices.
MediaKeyStatusMap.forEach() - Web APIs
syntax mediakeystatusmap.foreach(callback[, thisarg]) parameters callback function to execute for each element, taking three arguments: currentvalue the current element being processed in the array.
... index the index of the current element being processed in the array.
... array which array foreach() is being applied to.
MutationObserverInit.attributeFilter - Web APIs
the mutationobserverinit dictionary's optional attributefilter property is an array of strings specifying the names of the attributes whose values are to be monitored for changes.
... syntax var options = { attributefilter: [ "list", "of", "attribute", "names" ] } value an array of domstring objects, each specifying the name of one attribute whose value is to be monitored for changes.
... note the use of mutationrecord.oldvalue to get the previous value of the "username" property so we have that information when doing lookups in our local array of users.
Navigator.share() - Web APIs
WebAPINavigatorshare
files: a " frozenarray" representing the array of file to be shared.
...then include an array of files in the call to navigator.share(): notice: that the sample handles feature detection by testing for navigator.canshare() rather than for navigator.share().
... if (navigator.canshare && navigator.canshare({ files: filesarray })) { navigator.share({ files: filesarray, title: 'pictures', text: 'our pictures.', }) .then(() => console.log('share was successful.')) .catch((error) => console.log('sharing failed', error)); } else { console.log(`your system doesn't support sharing files.`); } specifications specification status comment web share apithe definition of 'share()' in that specification.
Navigator - Web APIs
WebAPINavigator
navigatorlanguage.languages read only returns an array of domstring representing the languages known to the user, by order of preference.
... navigatorplugins.mimetypes read only returns an mimetypearray listing the mime types supported by the browser.
... navigatorplugins.plugins read only returns a pluginarray listing the plugins installed in the browser.
NavigatorLanguage.languages - Web APIs
the navigatorlanguage.languages read-only property returns an array of domstrings representing the user's preferred languages.
...in the returned array they are ordered by preference with the most preferred language first.
... the value of navigator.language is the first element of the returned array.
NavigatorPlugins.mimeTypes - Web APIs
returns a mimetypearray object, which contains a list of mimetype objects representing the mime types recognized by the browser.
... note: named properties of mimetypearray objects are no longer enumerable in the latest browser versions.
... syntax var mimetypes[] = navigator.mimetypes; mimetypes is a mimetypearray object which has a length property as well as item(index) and nameditem(name) methods.
OVR_multiview2 - Web APIs
this extension is only available to webgl 2 contexts as it needs glsl 3.00 and texture arrays.
... methods framebuffertexturemultiviewovr() simultaneously renders to multiple elements of a 2d texture array.
... const gl = document.createelement('canvas').getcontext( 'webgl2', { antialias: false } ); const ext = gl.getextension('ovr_multiview2'); const fb = gl.createframebuffer(); gl.bindframebuffer(gl.draw_framebuffer, fb); const colortex = gl.createtexture(); gl.bindtexture(gl.texture_2d_array, colortex); gl.texstorage3d(gl.texture_2d_array, 1, gl.rgba8, 512, 512, 2); ext.framebuffertexturemultiviewovr(gl.draw_framebuffer, gl.color_attachment0, colortex, 0, 0, 2); const depthstenciltex = gl.createtexture(); gl.bindtexture(gl.texture_2d_array, depthstenciltex); gl.texstorage3d(gl.texture_2d_array, 1, gl.depth32f_stencil8, 512, 512, 2); ext.framebuffertexturemultiviewovr(gl.draw_frameb...
PaymentAddress.addressLine - Web APIs
the addressline read-only property of the paymentaddress interface is an array of domstring objects, each specifying a line of the address that is not covered by one of the other properties of paymentaddress.
... syntax var paymentaddresslines = paymentaddress.addressline; value an array of domstring objects, each containing one line of the address.
... for example, the addressline array for the mozilla space in london would have the following entries: example showing addressline entries for an address in london index addressline[] value 0 metal box factory 1 suite 441, 4th floor 2 30 great guildford street these, combined with additional values for other properties of the paymentaddress, would represent the full address, which is: mozilla metal box factory suite 441, 4th floor 30 great guildford street london se1 0hs united kingdom specifications specification status comment payment request apithe definition of 'paymentaddress.addressline' in that specification.
PaymentDetailsBase - Web APIs
properties displayitemsoptional an array of paymentitem objects, each describing one line item for the payment request.
... modifiersoptional an array of paymentdetailsmodifier objects, each describing a modifier for particular payment method identifiers.
... shippingoptionsoptional an array of paymentshippingoption objects, each describing one available shipping option from which the user may choose.
PaymentDetailsUpdate - Web APIs
displayitems optional an array of paymentitem objects, each describing one line item for the payment request.
... modifiers optional an array of paymentdetailsmodifier objects, each describing a modifier for particular payment method identifiers.
... shippingoptions optional an array of paymentshippingoption objects, each describing one available shipping option from which the user may choose.
PaymentRequestUpdateEvent.updateWith() - Web APIs
syntax paymentrequestupdateevent.updatewith(details); parameters details a paymentdetailsupdate object specifying the changes applied to the payment request: displayitems optional an array of paymentitem objects, each describing one line item for the payment request.
... modifiers optional an array of paymentdetailsmodifier objects, each describing a modifier for particular payment method identifiers.
... shippingoptions optional an array of paymentshippingoption objects, each describing one available shipping option from which the user may choose.
PeriodicWave.PeriodicWave() - Web APIs
options optional a periodicwaveoptions dictionary object defining the properties you want the periodicwave to have (it also inherits the options defined in the periodicwaveconstraints dictionary.): real: a float32array containing the cosine terms that you want to use to form the wave (equivalent to the real parameter of audiocontext.createperiodicwave).
... imag: a float32array containing the sine terms that you want to use to form the wave (equivalent to the imag parameter of audiocontext.createperiodicwave).
... example var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var options = { real : real, imag : imag, disablenormalization : false } var wave = new periodicwave(ac, options); specifications specification status comment web audio apithe definition of 'periodicwave' in that specification.
PublicKeyCredential.rawId - Web APIs
the rawid read-only property of the publickeycredential interface is an arraybuffer object containing the identifier of the credentials.
... syntax rawid = publickeycredential.rawid value a arraybuffer containing the identifier of the credentials.
... examples var options = { challenge: new uint8array(26) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey: options }) .then(function (pubkeycredential) { var rawid = pubkeycredential.rawid; // do something with rawid }).catch(function (err) { // deal with any error }); specifications specification status comment ...
PublicKeyCredential - Web APIs
publickeycredential.rawid read only secure context an arraybuffer that holds the globally unique identifier for this publickeycredential.
... var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var response = newcredentialinfo.response; var clientextensionsresults = newcredentialinfo.getclientextensionresults(); }).catch(function (err) { conso...
... var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'publickeycredential interface' in that specification.
PublicKeyCredentialRequestOptions - Web APIs
publickeycredentialrequestoptions.allowcredentials optional an array of credentials descriptor which restricts the acceptable existing credentials for retrieval.
... examples var options = { challenge: new uint8array([/* bytes sent from the server */]), rpid: "example.com", /* will only work if the current domain is something like foo.example.com */ userverification: "preferred", timeout: 60000, // wait for a minute allowcredentials: [ { transports: "usb", type: "public-key", id: new uint8array(26) // actually provided by the server }, { ...
... transports: "internal", type: "public-key", id: new uint8array(26) // actually provided by the server } ], extensions: { uvm: true, // rp wants to know how the user was verified loc: false, txauthsimple: "could you please verify yourself?" } }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'publickeycredentialrequestoptions dictionary' in that specification.
RTCPeerConnection.getDefaultIceServers() - Web APIs
the getdefaulticeservers() method of the rtcpeerconnection interface returns an array of objects based on the rtciceserver dictionary, which indicates what, if any, ice servers the browser will use by default if none are provided to the rtcpeerconnection in its rtcconfiguration.
... syntax var defaulticeservers = rtcpeerconnection.getdefaulticeservers(); return value an array of ice servers, specified as objects based on rtciceserver, which the browser will use if none are specified in the configuration of the rtcpeerconnection.
... if there are no defaults provided by the browser, the returned array is empty; this property's value is never null.
RTCPeerConnection.getReceivers() - Web APIs
the rtcpeerconnection.getreceivers() method returns an array of rtcrtpreceiver objects, each of which represents one rtp receiver.
... each rtp receiver manages the reception and decoding of data for a mediastreamtrack on an rtcpeerconnection syntax var receivers = rtcpeerconnection.getreceivers(); return value an array of rtcrtpreceiver objects, one for each track on the connection.
... the array is empty if there are no rtp receivers on the connection.
RTCPeerConnection.getSenders() - Web APIs
the rtcpeerconnection method getsenders() returns an array of rtcrtpsender objects, each of which represents the rtp sender responsible for transmitting one track's data.
... syntax var senders = rtcpeerconnection.getsenders(); return value an array of rtcrtpsender objects, one for each track on the connection.
... the array is empty if there are no rtp senders on the connection.
RTCPeerConnection - Web APIs
also included is a list of any ice candidates that may already have been generated by the ice agent since the offer or answer represented by the description was first instantiated.getdefaulticeservers() the getdefaulticeservers() method of the rtcpeerconnection interface returns an array of objects based on the rtciceserver dictionary, which indicates what, if any, ice servers the browser will use by default if none are provided to the rtcpeerconnection in its rtcconfiguration.
...this has an effect only if the signalingstate is not "closed".getreceivers() the rtcpeerconnection.getreceivers() method returns an array of rtcrtpreceiver objects, each of which represents one rtp receiver.
... each rtp receiver manages the reception and decoding of data for a mediastreamtrack on an rtcpeerconnectiongetsenders()the rtcpeerconnection method getsenders() returns an array of rtcrtpsender objects, each of which represents the rtp sender responsible for transmitting one track's data.getstats()the rtcpeerconnection method getstats() returns a promise which resolves with data providing statistics about either the overall connection or about the specified mediastreamtrack.getstreambyid() the rtcpeerconnection.getstreambyid() method returns the mediastream with the given id that is associated with local or remote end of the connection.
RTCTrackEvent - Web APIs
streams read only optional an array of mediastream objects, each representing one of the media streams to which the added track belongs.
... by default, the array is empty, indicating a streamless track.
... example this simple example creates an event listener for the track event which sets the srcobject of the <video> element with the id videobox to the first stream in the list passed in the event's streams array.
RTCTrackEventInit.streams - Web APIs
the rtctrackeventinit dictionary's optional streams property provides an array containing a mediastream object for each of the streams associated with the event's track.
... syntax var trackeventinit = { receiver: rtpreceiver, track: mediastreamtrack, streams: [videostream], transceiver: rtptransceiver }; var streamlist = trackeventinit.streams; value an array of mediastream objects, one for each stream which make up the track.
... if streams is not specified, its default value is an empty array.
ReadableStream - Web APIs
readablestream.tee() the tee method tees this readable stream, returning a two-element array containing the two resulting branches as new readablestream instances.
... it demonstrates the usage of a readablestream in combination with a uint8array.
... fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" reader.read().then(({ done, value }) => { // is there no more data to read?
ReadableStreamDefaultReader.read() - Web APIs
each chunk is read sequentially and output to the ui as an array of utf-8 bytes, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the ui.
... if (done) { console.log("stream complete"); para.textcontent = result; return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'received ' + charsreceived + ' characters so far.
...it deals with stream chunks not ending on line boundaries and converting from uint8array to strings.
ServiceWorkerContainer.getRegistrations() - Web APIs
the getregistrations() method of the serviceworkercontainer interface gets all serviceworkerregistrations associated with a serviceworkercontainer, in an array.
... the method returns a promise that resolves to an array of serviceworkerregistration.
... return value a promise that resolves to an array of serviceworkerregistration objects.
ServiceWorkerRegistration.showNotification() - Web APIs
it can have the following properties: actions: an array of actions to display in the notification.
... the members of the array should be an object literal.
...a vibration pattern can be an array with as few as one member.
Using Service Workers - Web APIs
if you just passed in the url, and then tried to access the other items in the json separately when the for() loop is being iterated through later on, it wouldn’t work, as the promise wouldn’t resolve at the same time as the iterations are being done (that is a synchronous process.) we actually resolve the promise with an array, as we want to make the loaded image blob available to the resolving function later on in the code, but also the image name, credits and alt text (see app.js lines 31-34).
... promises will only resolve with a single argument, so if you want to resolve with multiple values, you need to use an array/object.
...this returns a promise for a created cache; once resolved, we then call a function that calls addall() on the created cache, which for its parameter takes an array of origin-relative urls to all the resources you want to cache.
SpeechRecognitionEvent.results - Web APIs
when subsequent result events are fired, interim results may be overwritten by a newer interim result or by a final result — they may even be removed, if they are at the end of the "results" array and the array length decreases.
... // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
SpeechRecognitionEvent - Web APIs
speechrecognitionevent.resultindex read only returns the lowest index value result in the speechrecognitionresultlist "array" that has actually changed.
... // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
SpeechRecognitionResult.item() - Web APIs
the item getter of the speechrecognitionresult interface is a standard getter that allows speechrecognitionalternative objects within the result to be accessed via array syntax.
... // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
SpeechRecognitionResult.length - Web APIs
the length read-only property of the speechrecognitionresult interface returns the length of the "array" — the number of speechrecognitionalternative objects contained in the result (also referred to as "n-best alternatives".) the number of alternatives contained in the result depends on what the speechrecognition.maxalternatives property was set to when the speech recognition was first initiated.
... // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
SpeechRecognitionResult - Web APIs
speechrecognitionresult.length read only returns the length of the "array" — the number of speechrecognitionalternative objects contained in the result (also referred to as "n-best alternatives".) methods speechrecognitionresult.item a standard getter that allows speechrecognitionalternative objects within the result to be accessed via array syntax.
... // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
SpeechRecognitionResultList.item() - Web APIs
the item getter of the speechrecognitionresultlist interface is a standard getter — it allows speechrecognitionresult objects in the list to be accessed via array syntax.
... // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
SpeechRecognitionResultList.length - Web APIs
the length read-only property of the speechrecognitionresultlist interface returns the length of the "array" — the number of speechrecognitionresult objects in the list.
... // it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
StyleSheetList - Web APIs
it is an array-like object but can't be iterated over using array methods.
... however it can be iterated over in a standard for loop over its indices, or converted to an array.
... examples get document stylesheet objects with for loop for (let i = 0; i < document.stylesheets.length; i++) { let stylesheet = document.stylesheets[i]; } get all css rules for the document using array methods const allcss = [...document.stylesheets] .map(stylesheet => { try { return [...stylesheet.cssrules] .map(rule => rule.csstext) .join(''); } catch (e) { console.log('access to stylesheet %s is denied.
SubtleCrypto.generateKey() - Web APIs
keyusages is an array indicating what can be done with the newly generated key.
... possible values for array elements are: encrypt: the key may be used to encrypt messages.
... let keypair = window.crypto.subtle.generatekey( { name: "rsa-oaep", moduluslength: 4096, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256" }, true, ["encrypt", "decrypt"] ); elliptic curve key pair generation this code generates an ecdsa signing key pair.
TextDecoder - Web APIs
examples representing text with typed arrays this example shows how to decode a chinese/japanese character , as represented by five different typed arrays: uint8array, int8array, uint16array, int16array, and int32array.
... let utf8decoder = new textdecoder(); // default 'utf-8' or 'utf8' let u8arr = new uint8array([240, 160, 174, 183]); let i8arr = new int8array([-16, -96, -82, -73]); let u16arr = new uint16array([41200, 47022]); let i16arr = new int16array([-24336, -18514]); let i32arr = new int32array([-1213292304]); console.log(utf8decoder.decode(u8arr)); console.log(utf8decoder.decode(i8arr)); console.log(utf8decoder.decode(u16arr)); console.log(utf8decoder.decode(i16arr)); console.log(utf8decoder.decode(i32arr)); handling non-utf8 text in this example, we decode the russian text "Привет, мир!", which means "hello, world." in our textdecoder() constructor, we specify the windows-1251 character encoding, which is appropriate for cyrillic script.
... let win1251decoder = new textdecoder('windows-1251'); let bytes = new uint8array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]); console.log(win1251decoder.decode(bytes)); // Привет, мир!
WebGL2RenderingContext.compressedTexSubImage3D() - Web APIs
syntax // read from the buffer bound to gl.pixel_unpack_buffer void gl.compressedtexsubimage3d(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imagesize, offset); void gl.compressedtexsubimage3d(target, level, xoffset, yoffset, zoffset, width, height, depth, format, arraybufferview srcdata, optional srcoffset, optional srclengthoverride); parameters target a glenum specifying the binding point (target) of the active texture.
... gl.texture_2d_array: a two-dimensional array texture.
... srcdata an arraybufferview that be used as a data store for the compressed image data in memory.
WebGL2RenderingContext.copyBufferSubData() - Web APIs
possible values: gl.array_buffer: buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data.
... gl.element_array_buffer: buffer used for element indices.
... examples var srcbuffer = gl.createbuffer(); var dstbuffer = gl.createbuffer(); var data = new float32array(vertices); var length = vertices.length * 4; gl.bindbuffer(gl.array_buffer, srcbuffer); gl.bufferdata(gl.array_buffer, data, gl.static_draw); gl.bindbuffer(gl.copy_read_buffer, srcbuffer); gl.bindbuffer(gl.array_buffer, dstbuffer); gl.bufferdata(gl.array_buffer, new float32array(length), gl.static_draw); gl.copybuffersubdata(gl.copy_read_buffer, gl.array_buffer, 0, 0, length); specifications...
WebGLRenderingContext.bindTexture() - Web APIs
gl.texture_2d_array: a two-dimensional array texture.
... exceptions a gl.invalid_enum error is thrown if target is not gl.texture_2d, gl.texture_cube_map, gl.texture_3d, or gl.texture_2d_array.
... adds: gl.texture_3d and gl.texture_2d_array opengl es 3.0the definition of 'glbindtexture' in that specification.
WebGLRenderingContext.compressedTexSubImage2D() - Web APIs
syntax // webgl 1: void gl.compressedtexsubimage2d(target, level, xoffset, yoffset, width, height, format, arraybufferview?
... pixels); // additionally available in webgl 2: void gl.compressedtexsubimage2d(target, level, xoffset, yoffset, width, height, format, imagesize, offset); void gl.compressedtexsubimage2d(target, level, xoffset, yoffset, width, height, format, arraybufferview srcdata, optional srcoffset, optional srclengthoverride); parameters target a glenum specifying the binding point (target) of the active compressed texture.
... pixels an arraybufferview that be used as a data store for the compressed image data in memory.
WebGLRenderingContext.drawElements() - Web APIs
the webglrenderingcontext.drawelements() method of the webgl api renders primitives from array data.
... type a glenum specifying the type of the values in the element array buffer.
... possible values are: gl.unsigned_byte gl.unsigned_short when using the oes_element_index_uint extension: gl.unsigned_int offset a glintptr specifying a byte offset in the element array buffer.
WebGLRenderingContext.getBufferParameter() - Web APIs
possible values: gl.array_buffer: buffer containing vertex attributes, such as vertex coordinates, texture coordinate data, or vertex color data.
... gl.element_array_buffer: buffer used for element indices.
... examples gl.getbufferparameter(gl.array_buffer, gl.buffer_size); specifications specification status comment webgl 1.0the definition of 'getbufferparameter' in that specification.
WebGLRenderingContext.getSupportedExtensions() - Web APIs
syntax gl.getsupportedextensions(); return value an array of strings with all the supported webgl extensions.
... examples var canvas = document.getelementbyid('canvas'); gl = canvas.getcontext('webgl'); var extensions = gl.getsupportedextensions(); // array [ 'angle_instanced_arrays', 'ext_blend_minmax', ...
...the current extensions are: angle_instanced_arrays ext_blend_minmax ext_color_buffer_float ext_color_buffer_half_float ext_disjoint_timer_query ext_float_blend ext_frag_depth ext_srgb ext_shader_texture_lod ext_texture_compression_bptc ext_texture_compression_rgtc ext_texture_filter_anisotropic khr_parallel_shader_compile oes_element_index_uint oes_fbo_render_mipmap oes_standard_derivatives oes_texture_float oes_texture_float_linear oes_texture_half_float oes_texture_half_float_linear oes_vertex_array_object ovr_multiview2 webgl_color_buffer_float webgl_compressed_texture_ast...
WebGLRenderingContext.viewport() - Web APIs
to get this range, you can use the max_viewport_dims constant, which returns an int32array.
...int32array[16384, 16384] to get the current viewport, query the viewport constant.
...int32array[0, 0, 640, 480] specifications specification status comment webgl 1.0the definition of 'viewport' in that specification.
Compressed texture formats - Web APIs
which formats support texture_2d_array and texture_3d targets (in combination with compressedteximage3d) are noted in the following table.
... extension notes texture_2d_array texture_3d webgl_compressed_texture_astc yes yes webgl_compressed_texture_atc not usable with compressedtexsubimage2d/copytexsubimage2d.
... no examples async function getcompressedtextureifavailable(gl) { const texture = gl.createtexture(); gl.bindtexture(gl.texture_2d, texture); // create texture object on gpu const ext = gl.getextension('webgl_compressed_texture_s3tc'); // will be null if not supported if (ext) { // the file is already in the correct compressed format const dataarraybuffer = await fetch('/textures/foobar512x512.rgba_s3tc_dxt1') .then(response => response.arraybuffer()); gl.compressedteximage2d(gl.texture_2d, 0, // set the base image level ext.compressed_rgba_s3tc_dxt1_ext, // the compressed format we are using 512, 512, // width, height of the image 0, // border, always 0 new dataview(dataarraybuffer)); gl.generatem...
Using WebGL extensions - Web APIs
for instance: var ext = ( gl.getextension('oes_vertex_array_object') || gl.getextension('moz_oes_vertex_array_object') || gl.getextension('webkit_oes_vertex_array_object') ); note that, vendor prefix have been discouraged more and more and thus most browser implement experimental extensions behind a feature flag rather than vendor prefix.
... var available_extensions = gl.getsupportedextensions(); the webglrenderingcontext.getsupportedextensions() method returns an array of strings, one for each supported extension.
... extension list the current extensions are: angle_instanced_arrays ext_blend_minmax ext_color_buffer_float ext_color_buffer_half_float ext_disjoint_timer_query ext_float_blend ext_frag_depth ext_srgb ext_shader_texture_lod ext_texture_compression_bptc ext_texture_compression_rgtc ext_texture_filter_anisotropic khr_parallel_shader_compile oes_element_index_uint oes_fbo_render_mipmap oes_standard_derivatives oes_texture_float oes_texture_float_linear oes_texture_half_float oes_texture_half_float_linear oes_vertex_array_object ovr_multiview2 webgl_color_buffer_float webgl_compressed_texture_astc webgl_compressed_texture_atc webgl_compressed_texture_etc webgl_compressed_texture_etc1 webgl_compressed_texture_pvrtc webgl_compressed_texture_s3tc webgl_compressed_te...
WebGL: 2D and 3D graphics for the web - Web APIs
WebAPIWebGL API
reference standard interfaces webglrenderingcontext webgl2renderingcontext webglactiveinfo webglbuffer webglcontextevent webglframebuffer webglprogram webglquery webglrenderbuffer webglsampler webglshader webglshaderprecisionformat webglsync webgltexture webgltransformfeedback webgluniformlocation webglvertexarrayobject extensions angle_instanced_arrays ext_blend_minmax ext_color_buffer_float ext_color_buffer_half_float ext_disjoint_timer_query ext_float_blend ext_frag_depth ext_srgb ext_shader_texture_lod ext_texture_compression_bptc ext_texture_compression_rgtc ext_texture_filter_anisotropic khr_parallel_shader_compile oes_element_index_uint oes_fbo_render_mipmap oes_standard_deri...
...vatives oes_texture_float oes_texture_float_linear oes_texture_half_float oes_texture_half_float_linear oes_vertex_array_object ovr_multiview2 webgl_color_buffer_float webgl_compressed_texture_astc webgl_compressed_texture_atc webgl_compressed_texture_etc webgl_compressed_texture_etc1 webgl_compressed_texture_pvrtc webgl_compressed_texture_s3tc webgl_compressed_texture_s3tc_srgb webgl_debug_renderer_info webgl_debug_shaders webgl_depth_texture webgl_draw_buffers webgl_lose_context events webglcontextlost webglcontextrestored webglcontextcreationerror constants and types webgl constants webgl types webgl 2 webgl 2 is a major update to webgl which is provided through the webgl2renderingcontext interface.
... it is based on opengl es 3.0 and new features include: 3d textures, sampler objects, uniform buffer objects, sync objects, query objects, transform feedback objects, promoted extensions that are now core to webgl 2: vertex array objects, instancing, multiple render targets, fragment depth.
WebSocket.send() - Web APIs
WebAPIWebSocketsend
arraybuffer you can send the underlying binary data used by a typed array object; its binary data contents are queued in the buffer, increasing the value of bufferedamount by the requisite number of bytes.
... arraybufferview you can send any javascript typed array object as a binary frame; its binary data contents are queued in the buffer, increasing the value of bufferedamount by the requisite number of bytes.
... as of gecko 11.0, support for arraybuffer is implemented but not blob data types.
Writing WebSocket client applications - Web APIs
protocols optional either a single protocol string or an array of protocol strings.
... if you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols: var examplesocket = new websocket("wss://www.example.com/socketserver", ["protocolone", "protocoltwo"]); once the connection is established (that is, readystate is open), examplesocket.protocol will tell you which protocol the server selected.
...to do this, simply call the websocket object's send() method for each message you want to send: examplesocket.send("here's some text that the server is urgently awaiting!"); you can send data as a string, blob, or arraybuffer.
Inputs and input sources - Web APIs
profile strings each input source can have zero or more input profile name strings, found in the array profiles, each of which describes a preferred visual representation of the input source within the 3d world as well as how the input source functions.
... added an array of zero or more xrinputsource objects indicating the input sources that have been newly added to the xr system.
... removed an array of zero or more xrinputsource objects indicating any input sources that have been removed from the xr system.
Attestation and Assertion - Web APIs
the attestation format contains two basic arraybuffers: clientdatajson - an arraybuffer that contains a json representation of what the browser saw when being asked to authenticate.
...the assertion format is fairly simple as it contains four basic arraybuffers: clientdatajson - the same as in attestation.
... an arraybuffer that contains a json representation of what the browser saw when being asked to authenticate.
Web Authentication API - Web APIs
the publickeycredential is sent back to the server using any desired formatting and protocol (note that the arraybuffer properties need to be be base64 encoded or similar).
...- service): rp: { name: "acme" }, // user: user: { id: new uint8array(16), name: "john.p.smith@example.com", displayname: "john p.
... smith" }, pubkeycredparams: [{ type: "public-key", alg: -7 }], attestation: "direct", timeout: 60000, challenge: new uint8array([ // must be a cryptographically random number sent from a server 0x8c, 0x0a, 0x26, 0xff, 0x22, 0x91, 0xc1, 0xe9, 0xb9, 0x4e, 0x2e, 0x17, 0x1a, 0x98, 0x6a, 0x73, 0x71, 0x9d, 0x43, 0x48, 0xd5, 0xa7, 0x6a, 0x15, 0x7e, 0x38, 0x94, 0x52, 0x77, 0x97, 0x0f, 0xef ]).buffer } }; // sample arguments for login var getcredentialdefaultargs = { publickey: { timeout: 60000, // allowcredentials: [newcredential] // see below challenge: new uint8array([ // must be a cryptographically random number sent from a server 0x79, 0x50, 0x68,...
Window.frames - Web APIs
WebAPIWindowframes
returns the window itself, which is an array-like object, listing the direct sub-frames of the current window.
...it is similar to an array in that it has a length property and its items can be accessed using the [i] notation.
... each item in the window.frames pseudo-array represents the window object corresponding to the given <frame>'s or <iframe>'s content, not the (i)frame dom element (i.e., window.frames[0] is the same thing as document.getelementsbytagname("iframe")[0].contentwindow).
Window.openDialog() - Web APIs
WebAPIWindowopenDialog
the optional parameters, if present, are bundled up in a javascript array object and added to the newly created window as a property named window.arguments.
... passing extra parameters to the dialog to pass extra parameters into the dialog, you can simply supply them after the windowfeatures parameter: opendialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98); the extra parameters will then get packed into a property named arguments of type array, and this property gets added to the newly opened dialog window.
... var retvals = { address: null, delivery: null }; opendialog("http://example.tld/zzz.xul", "dlg", "modal", "pizza", 6.98, retvals); if you set the properties of the retvals object in the dialog code as described below, you can now access them via the retvals array after the opendialog() call returns.
Synchronous and asynchronous requests - Web APIs
*/) { var xhr = new xmlhttprequest(); xhr.callback = callback; xhr.arguments = array.prototype.slice.call(arguments, 2); xhr.onload = xhrsuccess; xhr.onerror = xhrerror; xhr.open("get", url, true); xhr.send(null); } usage: function showmessage(message) { console.log(message + this.responsetext); } loadfile("message.txt", showmessage, "new message!\n\n"); the signature of the utility function loadfile declares (i) a target url to read (via an http get req...
... line 12 slices the arguments array given to the invocation of loadfile.
...this is done by setting the value of the timeout property on the xmlhttprequest object, as shown in the code below: function loadfile(url, timeout, callback) { var args = array.prototype.slice.call(arguments, 3); var xhr = new xmlhttprequest(); xhr.ontimeout = function () { console.error("the request for " + url + " timed out."); }; xhr.onload = function() { if (xhr.readystate === 4) { if (xhr.status === 200) { callback.apply(xhr, args); } else { console.error(xhr.statustext); ...
XMLHttpRequest.send() - Web APIs
in file uploads) is by using an arraybufferview or blob in conjunction with the send() method.
...}; xhr.send(null); // xhr.send('string'); // xhr.send(new blob()); // xhr.send(new int8array()); // xhr.send(document); example: post var xhr = new xmlhttprequest(); xhr.open("post", '/server', true); //send the proper header information along with the request xhr.setrequestheader("content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { // call a function when the state changes.
... } } xhr.send("foo=bar&lorem=ipsum"); // xhr.send(new int8array()); // xhr.send(document); specifications specification status comment xmlhttprequestthe definition of 'send()' in that specification.
XMLHttpRequest - Web APIs
xmlhttprequest.response read only returns an arraybuffer, blob, document, javascript object, or a domstring, depending on the value of xmlhttprequest.responsetype, that contains the response entity body.
... xmlhttprequest.mozresponsearraybuffer obsolete since gecko 6 read only arraybuffer.
... the response to the request, as a javascript typed array.
XRRigidTransform - Web APIs
the advantage to using xrrigidtransform in these places rather than bare arrays that providing the matrix data is that the xrrigidtransform automatically does things like computing the inverse of the transform.
... xrrigidtransform.matrix read only returns the transform matrix in the form of a 16-member float32array.
... see the section matrix format for how the array is used to represent a matrix.
Closures - JavaScript
the helptext array defines three helpful hints, each associated with the id of an input field in the document.
...rather than the callbacks all sharing a single lexical environment, the makehelpcallback function creates a new lexical environment for each callback, in which help refers to the corresponding string from the helptext array.
... another alternative could be to use foreach() to iterate over the helptext array and attach a listener to each <p>, as shown: function showhelp(help) { document.getelementbyid('help').innerhtml = help; } function setuphelp() { var helptext = [ {'id': 'email', 'help': 'your e-mail address'}, {'id': 'name', 'help': 'your full name'}, {'id': 'age', 'help': 'your age (you must be over 16)'} ]; helptext.foreach(function(text) { document.getelemen...
Equality comparisons and sameness - JavaScript
there are four equality algorithms in es2015: abstract equality comparison (==) strict equality comparison (===): used by array.prototype.indexof, array.prototype.lastindexof, and case-matching samevaluezero: used by %typedarray% and arraybuffer constructors, as well as map and set operations, and also string.prototype.includes and array.prototype.includes since es2016 samevalue: used in all other places javascript provides three different value-comparison operations: === - strict equality comparison ("strict equality", "identity", "triple equals") == - abstract equality comparison ("loose equality", "double equals") object.is provides samevalue (new in es2015).
...however, since typed arrays are available, we can have distinct instances, which don't behave identically in all contexts.
... for example: var f2b = x => new uint8array(new float64array([x]).buffer); var b2f = x => new float64array(x.buffer)[0]; var n = f2b(nan); n[0] = 1; var nan2 = b2f(n); nan2; // > nan object.is(nan2, nan); // > true f2b(nan); // > uint8array(8) [0, 0, 0, 0, 0, 0, 248,127) f2b(nan2); // > uint8array(8) [1, 0, 0, 0, 0, 0, 248,127) ...
Text formatting - JavaScript
you can access each code unit using an array bracket style.
... you can't change individual characters because strings are immutable array-like objects: const hello = 'hello, world!'; const hellolength = hello.length; hello[0] = 'l'; // this has no effect, because strings are immutable hello[0]; // this returns "h" characters whose unicode scalar values are greater than u+ffff (such as some rare chinese/japanese/korean/vietnamese characters and some emoji) are stored in utf-16 with two surrogate code units each.
... split splits a string object into an array of strings by separating the string into substrings.
Memory Management - JavaScript
var n = 123; // allocates memory for a number var s = 'azerty'; // allocates memory for a string var o = { a: 1, b: null }; // allocates memory for an object and contained values // (like object) allocates memory for the array and // contained values var a = [1, null, 'abra']; function f(a) { return a + 2; } // allocates a function (which is a callable object) // function expressions also allocate an object someelement.addeventlistener('click', function() { someelement.style.backgroundcolor = 'blue'; }, false); allocation via function calls some function calls result in object allocation.
... var a = ['ouais ouais', 'nan nan']; var a2 = ['generation', 'nan nan']; var a3 = a.concat(a2); // new array with 4 elements being // the concatenation of a and a2 elements.
...cycles are a common mistake that can generate memory leaks: var div; window.onload = function() { div = document.getelementbyid('mydivelement'); div.circularreference = div; div.lotsofdata = new array(10000).join('*'); }; in the above example, the dom element "mydivelement" has a circular reference to itself in the "circularreference" property.
Classes - JavaScript
species you might want to return array objects in your derived array class myarray.
... for example, when using methods such as map() that returns the default constructor, you want these methods to return a parent array object, instead of the myarray object.
... the symbol.species symbol lets you do this: class myarray extends array { // overwrite species to the parent array constructor static get [symbol.species]() { return array; } } let a = new myarray(1,2,3); let mapped = a.map(x => x * x); console.log(mapped instanceof myarray); // false console.log(mapped instanceof array); // true super class calls with super the super keyword is used to call corresponding methods of super class.
SyntaxError: missing ] after element list - JavaScript
the javascript exception "missing ] after element list" occurs when there is an error with the array initializer syntax somewhere.
... there is an error with the array initializer syntax somewhere.
... examples incomplete array initializer var list = [1, 2, var instruments = [ 'ukulele', 'guitar', 'piano' }; var data = [{foo: 'bar'} {bar: 'foo'}]; correct would be: var list = [1, 2]; var instruments = [ 'ukulele', 'guitar', 'piano' ]; var data = [{foo: 'bar'}, {bar: 'foo'}]; ...
JavaScript error reference - JavaScript
error: permission denied to access property "x"internalerror: too much recursionrangeerror: argument is not a valid code pointrangeerror: invalid array lengthrangeerror: invalid daterangeerror: precision is out of rangerangeerror: radix must be an integerrangeerror: repeat count must be less than infinityrangeerror: repeat count must be non-negativereferenceerror: "x" is not definedreferenceerror: assignment to undeclared variable "x"referenceerror: can't access lexical declaration "x" before initializationreferenceerror: deprecated caller or ar...
... not in functionsyntaxerror: test for equality (==) mistyped as assignment (=)?syntaxerror: unterminated string literaltypeerror: "x" has no propertiestypeerror: "x" is (not) "y"typeerror: "x" is not a constructortypeerror: "x" is not a functiontypeerror: "x" is not a non-null objecttypeerror: "x" is read-onlytypeerror: 'x' is not iterabletypeerror: more arguments neededtypeerror: reduce of empty array with no initial valuetypeerror: x.prototype.y called on incompatible typetypeerror: can't access dead objecttypeerror: can't access property "x" of "y"typeerror: can't assign to property "x" on "y": not an objecttypeerror: can't define property "x": "obj" is not extensibletypeerror: can't delete non-configurable array elementtypeerror: can't redefine non-configurable property "x"typeerror: cannot...
... use "in" operator to search for "x" in "y"typeerror: cyclic object valuetypeerror: invalid "instanceof" operand "x"typeerror: invalid array.prototype.sort argumenttypeerror: invalid argumentstypeerror: invalid assignment to const "x"typeerror: property "x" is non-configurable and can't be deletedtypeerror: setting getter-only property "x"typeerror: variable "x" redeclares argumenturierror: malformed uri sequencewarning: 08/09 is not a legal ecma-262 octal constantwarning: -file- is being assigned a //# sourcemappingurl, but already has onewarning: date.prototype.tolocaleformat is deprecatedwarning: javascript 1.6's for-each-in loops are deprecatedwarning: string.x is deprecated; use string.prototype.x insteadwarning: expression closures are deprecatedwarning: unreachable code after return stat...
DataView.prototype.byteLength - JavaScript
the bytelength accessor property represents the length (in bytes) of this view from the start of its arraybuffer or sharedarraybuffer.
...if the dataview is not specifying an offset or a bytelength, the bytelength of the referenced arraybuffer or sharedarraybuffer will be returned.
... examples using the bytelength property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.bytelength; // 8 (matches the bytelength of the buffer) var dataview2 = new dataview(buffer, 1, 5); dataview2.bytelength; // 5 (as specified when constructing the dataview) var dataview3 = new dataview(buffer, 2); dataview3.bytelength; // 6 (due to the offset of the constructed dataview) specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.bytelength' in that specification.
Function.prototype.call() - JavaScript
note: while the syntax of this function is almost identical to that of apply(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.
...} function food(name, price) { product.call(this, name, price); this.category = 'food'; } function toy(name, price) { product.call(this, name, price); this.category = 'toy'; } const cheese = new food('feta', 5); const fun = new toy('robot', 40); using call to invoke an anonymous function in this example, we create an anonymous function and use call to invoke it on every object in an array.
... the main purpose of the anonymous function here is to add a print function to every object, which is able to print the correct index of the object in the array.
Function - JavaScript
instance properties function.arguments an array corresponding to the arguments passed to a function.
... instance methods function.prototype.apply(thisarg [, argsarray]) calls a function and sets its this to the provided thisarg.
... arguments can be passed as an array object.
Intl.Collator.prototype.compare() - JavaScript
examples using compare for array sort use the compare getter function for sorting arrays.
... note that the function is bound to the collator from which it was obtained, so it can be passed directly to array.prototype.sort().
... var a = ['offenbach', 'Österreich', 'odenwald']; var collator = new intl.collator('de-u-co-phonebk'); a.sort(collator.compare); console.log(a.join(', ')); // → "odenwald, Österreich, offenbach" using compare for array search use the compare getter function for finding matching strings in arrays: var a = ['congrès', 'congres', 'assemblée', 'poisson']; var collator = new intl.collator('fr', { usage: 'search', sensitivity: 'base' }); var s = 'congres'; var matches = a.filter(v => collator.compare(v, s) === 0); console.log(matches.join(', ')); // → "congrès, congres" specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.collator.prototype.compare' in that specification.
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
return value an array of objects containing the formatted date in parts.
...it returns an array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts.
...for example by using array.prototype.map(), arrow functions, a switch statement, template literals, and array.prototype.reduce().
Intl.DateTimeFormat - JavaScript
static methods intl.datetimeformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
... intl.datetimeformat.prototype.formattoparts() returns an array of objects representing the date string in parts that can be used for custom locale-aware formatting.
... intl.datetimeformat.prototype.formatrangetoparts() this method receives two dates and returns an array of objects containing the locale-specific tokens representing each part of the formatted date range.
Intl.NumberFormat.prototype.formatToParts() - JavaScript
return value an array of objects containing the formatted number in parts.
...it returns an array of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts.
...for example by using array.prototype.map(), arrow functions, a switch statement, template literals, and array.prototype.reduce().
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
the intl.relativetimeformat.prototype.formattoparts() method returns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting.
... return value an array of objects containing the formatted relative time in parts.
... description the intl.relativetimeformat.prototype.formattoparts method is a version of the format method which it returns an array of objects which represent "parts" of the object, separating the formatted number into its consituent parts and separating it from other surrounding text.
Object.fromEntries() - JavaScript
syntax object.fromentries(iterable); parameters iterable an iterable such as array or map or other objects implementing the iterable protocol.
...the iterable argument is expected to be an object that implements an @@iterator method, that returns an iterator object, that produces a two element array-like object, whose first element is a value that will be used as a property key, and whose second element is the value to associate with that property key.
... examples converting a map to an object with object.fromentries, you can convert from map to object: const map = new map([ ['foo', 'bar'], ['baz', 42] ]); const obj = object.fromentries(map); console.log(obj); // { foo: "bar", baz: 42 } converting an array to an object with object.fromentries, you can convert from array to object: const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]; const obj = object.fromentries(arr); console.log(obj); // { 0: "a", 1: "b", 2: "c" } object transformations with object.fromentries, its reverse method object.entries(), and array manipulation methods, you are able to transform objects like this: const object1 = { a: 1, b: 2, c: 3 }; const object2 = object.fromentries( object.entries(objec...
Promise.any() - JavaScript
syntax promise.any(iterable); parameters iterable an iterable object, such as an array.
...unlike promise.all(), which returns an array of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills).
... rejection if all of the passed-in promises reject, promise.any asynchronously rejects with an aggregateerror object, which extends error, and contains an errors property with an array of rejection values.
Promise.race() - JavaScript
syntax promise.race(iterable); parameters iterable an iterable object, such as an array.
... examples asynchronicity of promise.race this following example demonstrates the asynchronicity of promise.race: // we are passing as argument an array of promises that are already resolved, // to trigger promise.race as soon as possible var resolvedpromisesarray = [promise.resolve(33), promise.resolve(44)]; var p = promise.race(resolvedpromisesarray); // immediately logging the value of p console.log(p); // using settimeout we can execute code after the stack is empty settimeout(function(){ console.log('the stack is now empty'); conso...
...gpromise); settimeout(function(){ console.log('the stack is now empty'); console.log(foreverpendingpromise); }); // logs, in order: // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "pending" } if the iterable contains one or more non-promise value and/or an already settled promise, then promise.race will resolve to the first of these values found in the array: var foreverpendingpromise = promise.race([]); var alreadyfulfilledprom = promise.resolve(100); var arr = [foreverpendingpromise, alreadyfulfilledprom, "non-promise value"]; var arr2 = [foreverpendingpromise, "non-promise value", promise.resolve(100)]; var p = promise.race(arr); var p2 = promise.race(arr2); console.log(p); console.log(p2); settimeout(function(){ console.log('the stack is n...
handler.ownKeys() - JavaScript
interceptions this trap can intercept these operations: object.getownpropertynames() object.getownpropertysymbols() object.keys() reflect.ownkeys() invariants if the following invariants are violated, the proxy will throw a typeerror: the result of ownkeys() must be an array.
... the type of each array element is either a string or a symbol.
... const obj = {}; object.defineproperty(obj, 'a', { configurable: false, enumerable: true, value: 10 } ); const p = new proxy(obj, { ownkeys: function(target) { return [123, 12.5, true, false, undefined, null, {}, []]; } }); console.log(object.getownpropertynames(p)); // typeerror: proxy [[ownpropertykeys]] must return an array // with only string and symbol elements specifications specification ecmascript (ecma-262)the definition of '[[ownpropertykeys]]' in that specification.
Proxy - JavaScript
elected')); // 'true' let i2 = view.selected = document.getelementbyid('item-2'); console.log(i1.getattribute('aria-selected')); // 'false' console.log(i2.getattribute('aria-selected')); // 'true' note: even if selected: !null, then giving oldval.setattribute is not a function value correction and an extra property the products proxy object evaluates the passed value and converts it to an array if needed.
... prop) { // an extra property if (prop === 'latestbrowser') { return obj.browsers[obj.browsers.length - 1]; } // the default behavior to return the value return obj[prop]; }, set: function(obj, prop, value) { // an extra property if (prop === 'latestbrowser') { obj.browsers.push(value); return true; } // convert the value if it is not an array if (typeof value === 'string') { value = [value]; } // the default behavior to store the value obj[prop] = value; // indicate success return true; } }); console.log(products.browsers); // ['internet explorer', 'netscape'] products.browsers = 'firefox'; // pass a string (by mistake) console.log(products.browsers); // ['firefox'] <- no problem, the value is a...
...n array products.latestbrowser = 'chrome'; console.log(products.browsers); // ['firefox', 'chrome'] console.log(products.latestbrowser); // 'chrome' finding an array item object by its property this proxy extends an array with some utility features.
Reflect.ownKeys() - JavaScript
the static reflect.ownkeys() method returns an array of the target object's own property keys.
... return value an array of the target object's own property keys.
... description the reflect.ownkeys method returns an array of the target object's own property keys.
Set.prototype.entries() - JavaScript
the entries() method returns a new iterator object that contains an array of [value, value] for each element in the set object, in insertion order.
...however, to keep the api similar to the map object, each entry has the same value for its key and value here, so that an array [value, value] is returned.
... syntax myset.entries() return value a new iterator object that contains an array of [value, value] for each element in the given set, in insertion order.
Symbol.species - JavaScript
property attributes of symbol.species writable no enumerable no configurable no examples using species you might want to return array objects in your derived array class myarray.
... for example, when using methods such as map() that return the default constructor, you want these methods to return a parent array object, instead of the myarray object.
... the species symbol lets you do this: class myarray extends array { // overwrite species to the parent array constructor static get [symbol.species]() { return array; } } let a = new myarray(1,2,3); let mapped = a.map(x => x * x); console.log(mapped instanceof myarray); // false console.log(mapped instanceof array); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.species' in that specification.
Symbol.unscopables - JavaScript
however, in ecmascript 2015 and later, the array.prototype.keys() method was introduced.
...a built-in unscopables setting is implemented as array.prototype[@@unscopables] to prevent that some of the array methods are being scoped into the with statement.
... var keys = []; with (array.prototype) { keys.push('something'); } object.keys(array.prototype[symbol.unscopables]); // ["copywithin", "entries", "fill", "find", "findindex", // "includes", "keys", "values"] unscopables in objects you can also set unscopables for your own objects.
WebAssembly.compile() - JavaScript
syntax promise<webassembly.module> webassembly.compile(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile.
... exceptions if buffersource is not a typed array, a typeerror is thrown.
... var worker = new worker("wasm_worker.js"); fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.compile(bytes) ).then(mod => worker.postmessage(mod) ); note: you'll probably want to use webassembly.compilestreaming() in most cases, as it is more efficient than compile().
WebAssembly - JavaScript
webassembly.memory() an object whose buffer property is a resizable arraybuffer that holds the raw bytes of memory accessed by a webassembly instance.
... webassembly.table() an array-like structure representing a webassembly table, which stores function references.
... webassembly.validate() validates a given typed array of webassembly binary code, returning whether the bytes are valid webassembly code (true) or not (false).
Standard built-in objects - JavaScript
this includes (typed) arrays and array-like constructs.
... array int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array keyed collections these objects represent collections which use keys.
... arraybuffer sharedarraybuffer atomics dataview json control abstraction objects control abstractions can help to structure code, especially async code (without using deeply nested callbacks, for example).
Comma operator (,) - JavaScript
the comma operator is fully different from the comma within arrays, objects, and function arguments and parameters.
... examples if a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once.
... the following code prints the values of the diagonal elements in the array: for (var i = 0, j = 9; i <= 9; i++, j--) console.log('a[' + i + '][' + j + '] = ' + a[i][j]); note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression.
Expressions and operators - JavaScript
[] array initializer/literal syntax.
... ...obj spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
... [a, b] = [1, 2] {a, b} = {a:1, b:2} destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.
const - JavaScript
t my_fav = 20; // my_fav is now 20 console.log('my favorite number is ' + my_fav); // this gets hoisted into the global context and throws an error var my_fav = 20; } // my_fav is still 7 console.log('my favorite number is ' + my_fav); const needs to be initialized // throws an error // uncaught syntaxerror: missing initializer in const declaration const foo; const in objects and arrays const also works on objects and arrays.
...my_object = {'other_key': 'value'}; // however, object keys are not protected, // so the following statement is executed without problem my_object.key = 'othervalue'; // use object.freeze() to make object immutable // the same applies to arrays const my_array = []; // it's possible to push items into the array my_array.push('a'); // ["a"] // however, assigning a new array to the variable throws an error // uncaught typeerror: assignment to constant variable.
... my_array = ['b']; specifications specification ecmascript (ecma-262)the definition of 'let and const declarations' in that specification.
Template literals (Template strings) - JavaScript
the first argument of a tag function contains an array of string values.
... let str = string.raw`hi\n${2+3}!`; // "hi\n5!" str.length; // 6 array.from(str).join(','); // "h,i,\,n,5,!" tagged templates and escape sequences es2016 behavior as of ecmascript 2016, tagged templates conform to the rules of the following escape sequences: unicode escapes started by "\u", for example \u00a9 unicode code point escapes indicated by "\u{}", for example \u{2f804} hexadecimal escapes started by "\x", for example \xa9 octal literal escapes sta...
...they will show up as undefined element in the “cooked” array: function latex(str) { return { "cooked": str[0], "raw": str.raw[0] } } latex`\unicode` // { cooked: undefined, raw: "\\unicode" } note that the escape sequence restriction is only dropped from tagged templates—not from untagged template literals: let bad = `bad escape sequence: \unicode`; specifications specification ecmascript (ecma-262)the definition of 'templa...
JavaScript
the complete modules available there are as follows: javascript first steps answers some fundamental questions such as "what is javascript?", "what does it look like?", and "what can it do?", along with discussing key javascript features such as variables, strings, numbers, and arrays.
... javascript typed arrays javascript typed arrays provide a mechanism for accessing raw binary data.
... standard objects get to know standard built-in objects array, boolean, date, error, function, json, math, number, object, regexp, string, map, set, weakmap, weakset, and others.
<mmultiscripts> - MathML
the degree of a tensor depends on the dimensionality of a representative array.
... for example, a number is a 0-dimensional array, or a 0th-order tensor.
... a 1-dimensional array (e.g.
MathML documentation index - MathML
WebMathMLIndex
the degree of a tensor depends on the dimensionality of a representative array.
... for example, a number is a 0-dimensional array, or a 0th-order tensor.
... a 1-dimensional array (e.g.
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
first, a variable for storing the cache name is created, and the app shell files are listed in one array.
...'/pwa-examples/js13kpwa/icons/icon-96.png', '/pwa-examples/js13kpwa/icons/icon-128.png', '/pwa-examples/js13kpwa/icons/icon-168.png', '/pwa-examples/js13kpwa/icons/icon-192.png', '/pwa-examples/js13kpwa/icons/icon-256.png', '/pwa-examples/js13kpwa/icons/icon-512.png' ]; next, the links to images to be loaded along with the content from the data/games.js file are generated in the second array.
... after that, both arrays are merged using the array.prototype.concat() function.
SVG Presentation Attributes - SVG: Scalable Vector Graphics
lor flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-orientation-horizontal glyph-orientation-vertical image-rendering kerning letter-spacing lighting-color marker-end marker-mid marker-start mask opacity overflow pointer-events shape-rendering solid-color solid-opacity stop-color stop-opacity stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering transform unicode-bidi vector-effect visibility word-spacing writing-mode attributes alignment-baseline it specifies how an object is aligned along the font baseline with respect to its parent.
... value: <paint>; animatable: yes stroke-dasharray defines the pattern of dashes and gaps used to paint the outline of the shape.
... value: none|<dasharray>; animatable: yes stroke-dashoffset defines an offset on the rendering of the associated dash array.
stroke-dashoffset - SVG: Scalable Vector Graphics
the stroke-dashoffset attribute is a presentation attribute defining an offset on the rendering of the associated dash array.
... as a presentation attribute, it can be applied to any element but it has effect only on the following twelve elements: <altglyph>, <circle>, <ellipse>, <path>, <line>, <polygon>, <polyline>, <rect>, <text>, <textpath>, <tref>, and <tspan> html,body,svg { height:100% } <svg viewbox="-3 0 33 10" xmlns="http://www.w3.org/2000/svg"> <!-- no dash array --> <line x1="0" y1="1" x2="30" y2="1" stroke="black" /> <!-- no dash offset --> <line x1="0" y1="3" x2="30" y2="3" stroke="black" stroke-dasharray="3 1" /> <!-- the start of the dash array computation is pulled by 3 user units --> <line x1="0" y1="5" x2="30" y2="5" stroke="black" stroke-dasharray="3 1" stroke-dashoffset="3" /> <!-- the start of t...
...he dash array computation is pushed by 3 user units --> <line x1="0" y1="7" x2="30" y2="7" stroke="black" stroke-dasharray="3 1" stroke-dashoffset="-3" /> <!-- the start of the dash array computation is pulled by 1 user units which ends up in the same rendering as the previous example --> <line x1="0" y1="9" x2="30" y2="9" stroke="black" stroke-dasharray="3 1" stroke-dashoffset="1" /> <!-- the following red lines highlight the offset of the dash array for each line --> <path d="m0,5 h-3 m0,7 h3 m0,9 h-1" stroke="rgba(255,0,0,.5)" /> </svg> usage notes value <percentage> | <length> default value 0 animatable yes the offset is usually expressed in user units resolved against the pathle...
port - Archive of obsolete content
this means that it needs to be a string, number, boolean, null, array of json-serializable values, or an object whose property values are themselves json-serializable.
... for example, to include an array of strings in the payload: // main.js var pagemods = require("sdk/page-mod"); var self = require("sdk/self"); var pagemod = pagemods.pagemod({ include: ['*'], contentscriptfile: self.data.url("content-script.js"), onattach: setuplistener }); function setuplistener(worker) { worker.port.on('loaded', function(pageinfo) { console.log(pageinfo[0]); console.log(pageinfo[1]); }); } //content-script.js self.port.emit('loaded', [ document.location.tostring(), document.title ]); ...
Communicating using "port" - Archive of obsolete content
this means that it needs to be a string, number, boolean, null, array of json-serializable values, or an object whose property values are themselves json-serializable.
... for example, to include an array of strings in the payload: var pagemodscript = "self.port.emit('loaded'," + " [" + " document.location.tostring()," + " document.title" + " ]" + ");" var pagemod = require('page-mod').pagemod({ include: ['*'], contentscript: pagemodscript, onattach: function(worker) { worker.port.on('loaded', function(pageinfo) { console.log(pageinfo[0]); console.log(pageinfo[1]); }); } }); ...
Content Scripts - Archive of obsolete content
you can load multiple scripts by passing an array of strings to either contentscript or contentscriptfile: // main.js var tabs = require("sdk/tabs"); tabs.on('ready', function(tab) { tab.attach({ contentscript: ['document.body.style.border = "5px solid red";', 'window.alert("hi");'] }); }); // main.js var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", conte...
...on options the contentscriptoptions is a json object that is exposed to content scripts as a read-only value under the self.options property: // main.js var tabs = require("sdk/tabs"); tabs.on('ready', function(tab) { tab.attach({ contentscript: 'window.alert(self.options.message);', contentscriptoptions: {"message" : "hello world"} }); }); any kind of jsonable value (object, array, string, etc.) can be used here.
tabs - Archive of obsolete content
example var tabs = require("sdk/tabs"); tabs.on('ready', function(tab) { var worker = tab.attach({ contentscript: 'document.body.style.border = "5px solid red";' }); }); parameters options : object optional options: name type contentscriptfile string,array the local file urls of content scripts to load.
... contentscript string,array a string or an array of strings of code to be evaluated in the context.
/loader - Archive of obsolete content
these modules don't share scope and get their own set of built-ins (object, array, string ...).
...in such cases you can create a requirer module instance and a version of require exposed to it with this function: let requirer = module(requirerid, requireruri); let require = require(loader, requirer); let boostrap = require(bootstrapid); resolveuri() this function is used by the loader to resolve module uri from an id using a mapping array generated from the loader's paths option.
content/symbiont - Archive of obsolete content
any kind of jsonable value (object, array, string, etc.) can be used here.
... any kind of jsonable value (object, array, string, etc.) can be used here.
content/worker - Archive of obsolete content
optional options: name type contentscriptfile string,array the local file urls of content scripts to load.
... contentscript string,array the texts of content scripts to load.
io/file - Archive of obsolete content
list(path) returns an array of file names in the given directory.
... returns array : an array of file names.
lang/functional - Archive of obsolete content
let { invoke } = require("sdk/lang/functional"); invoke(sum, [1,2,3,4,5], null); // 15 function sum () { return array.slice(arguments).reduce(function (a, b) { return a + b; }); } parameters callee : function function to invoke.
... params : array parameters to be passed into callee.
tabs/utils - Archive of obsolete content
returns array : an array of tab elements.
... returns array : array of windows.
test/assert - Archive of obsolete content
for all other object pairs, including array objects, equivalence is determined by having the same number of owned properties (as verified with object.prototype.hasownproperty.call), the same set of keys (although not necessarily the same order), equivalent values for every corresponding key, and an identical "prototype" property.
... note: this accounts for both named and indexed properties on arrays.
util/list - Archive of obsolete content
list is composed out of iterable, therefore it provides custom enumeration behavior that is similar to array (enumerates only on the elements of the list).
... examples: var { list } = require("sdk/util/list"); var mylist = list.compose({ add: function add(item1, item2, /*item3...*/) { array.slice(arguments).foreach(this._add.bind(this)); }, remove: function remove(item1, item2, /*item3...*/) { array.slice(arguments).foreach(this._remove.bind(this)); } }); mylist('foo', 'bar', 'baz').length == 3; // true new mylist('new', 'keyword').length == 2; // true mylist.apply(null, [1, 2, 3]).length == 3; // true let list = mylist(); list.length == 0; // true list.add(1, 2, 3) == 3; // true properties length number of elements in this list.
Displaying annotations - Archive of obsolete content
updating main.js first, initialize an array to hold workers associated with the matcher's content scripts: var matchers = []; in the main function, add the code to create the matcher: var matcher = pagemod.pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('matcher.js')], onattach: function(worker) { if(simplestorage.storage.annotations) {...
...this function: initializes the content script instance with the current set of annotations provides a handler for messages from that content script, handling the three messages - show, hide and detach - that the content script might send adds the worker to an array, so we it can send messages back later.
Miscellaneous - Archive of obsolete content
("invalid.url")) another similar alternative (using both getstringfromname and formatstringfromname), is: var fcbundle = components.classes["@mozilla.org/intl/stringbundle;1"] .getservice(components.interfaces.nsistringbundleservice) .createbundle("chrome://myext/locale/myext.properties"); function getstr(msg, args){ //get localised message if (args){ args = array.prototype.slice.call(arguments, 1); return fcbundle.formatstringfromname(msg,args,args.length); } else { return fcbundle.getstringfromname(msg); } } /* usage */ alert(getstr("invalid.url", "http://bad/url/", "3")); //for message with parameters alert(getstr("invalid.url")); //for message without parameters getting postdata of a webpage first, you need to get the browser you want, ...
...and here's how it's done postdata.queryinterface(ci.nsiseekablestream).seek(ci.nsiseekablestream.ns_seek_set, 0); var stream = cc["@mozilla.org/binaryinputstream;1"].createinstance(ci.nsibinaryinputstream); stream.setinputstream(postdata); var postbytes = stream.readbytearray(stream.available()); var poststr = string.fromcharcode.apply(null, postbytes); //do anything to your poststr alert(poststr); getting a string from the input stream is made somewhat simpler in firefox 4, by the addition of netutil.readinputstreamtostring() getting postdata of a request before the request is sent the above code will get the postdata for a page that has already loaded.
Rosetta - Archive of obsolete content
nevertheless, the increasing computational power of modern browsers together with the introduction of typed arrays in ecmascript allow us, in theory, to build full virtual machines in pure ecmascript.
...escript = parsescript; this.translateall = parsedocument; this.appendcompiler = function (vmimetypes, fcompiler) { if (arguments.length < 2) { throw new typeerror("rosetta.appendcompiler() \u2013 not enough arguments"); } if (typeof fcompiler !== "function") { throw new typeerror("rosetta.appendcompiler() \u2013 second argument must be a function"); } if (!array.isarray(vmimetypes)) { odicts[(vmimetypes).tostring()] = fcompiler; return true; } for (var nidx = 0; nidx < vmimetypes.length; nidx++) { odicts[(vmimetypes[nidx]).tostring()] = fcompiler; } return true; }; })(); now, imagine you need a compiler for scripts written in c (mime type: text/x-c).
Appendix D: Loading Scripts - Archive of obsolete content
because there are such a diverse array of add-ons, and because the needs of developers have grown organically over time, the gecko runtime provides a number of means to dynamically load and execute javascript files.
...all variables named in the target script's exported_symbols global array will be copied into the current execution context.
JavaScript Object Management - Archive of obsolete content
*/ init : function() { this.obsservice = cc["@mozilla.org/observer-service;1"].getservice(ci.nsiobserverservice); } }; 〈namespace〉.init(); }; js objects can also be treated as string-indexed arrays: // equivalent.
...data will often be translated into arrays of entities, and those are better represented through classes.
Index of archived content - Archive of obsolete content
system/runtime system/unload system/xul-app tabs/utils test/assert test/harness test/httpd test/runner test/utils ui/button/action ui/button/toggle ui/frame ui/id ui/sidebar ui/toolbar util/array util/collection util/deprecate util/list util/match-pattern util/object util/uuid window/utils release notes tools cfx cfx to jpm console jpm jpm-mobile...
...namespaces the global xml object iterator liveconnect liveconnect overview liveconnect reference jsexception jsobject msx emulator (jsmsx) old proxy api parallelarray properly using css and javascript in xhtml documents examples reference server-side javascript back to the server: server-side javascript on the rise sharp variables in javascript standards-compliant authoring tools stopi...
Creating a Web based tone generator - Archive of obsolete content
tail = tail.subarray(written); return; // ...
... var sounddata = new float32array(parsefloat(available)); readfn(sounddata); // writing the data.
Visualizing an audio spectrum - Archive of obsolete content
dmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; fft = new fft(framebufferlength / channels, rate); } function audioavailable(event) { var fb = event.framebuffer, t = event.time, /* unused, but it's there */ signal = new float32array(fb.length / channels), magnitude; for (var i = 0, fbl = framebufferlength / 2; i < fbl; i++ ) { // assuming interlaced stereo channels, // need to split and merge into a stero-mix mono signal signal[i] = (fb[2*i] + fb[2*i+1]) / 2; } fft.forward(signal); // clear the canvas before drawing spectrum ctx.clearrect(0,...
...dio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); // fft from dsp.js, see below var fft = function(buffersize, samplerate) { this.buffersize = buffersize; this.samplerate = samplerate; this.spectrum = new float32array(buffersize/2); this.real = new float32array(buffersize); this.imag = new float32array(buffersize); this.reversetable = new uint32array(buffersize); this.sintable = new float32array(buffersize); this.costable = new float32array(buffersize); var limit = 1, bit = buffersize >> 1; while ( limit < buffersize ...
Enabling Experimental Jetpack Features - Archive of obsolete content
list() arrayreturns an array of the set of potential stringmountpath as used in jetpack.future.import().
... this is an example of how to get this array.
Enabling - Archive of obsolete content
list()returns an array of the set of potential stringmountpath as used in jetpack.future.import().
... this is an example of how to get this array.
Enabling Experimental Jetpack Features - Archive of obsolete content
ArchiveMozillaJetpackdocsMetaFuture
list() arrayreturns an array of the set of potential stringmountpath as used in jetpack.future.import().
... this is an example of how to get this array.
File object - Archive of obsolete content
file.readall() read the entire file in, returning an array of lines.
... file.writeall() writes an array of lines to the file, obeying the same semantics as writeln.
Table Cellmap - Archive of obsolete content
insertrowsbefore firstrow=0 ***start table dump*** mcolwidths= row(0)=02763344 cell(0)=02763528 cell(0)=0276381c row(0)=02763940 cell(0)=02763990 cell(0)=02763ab4 ***** start table cell map dump ***** 023566b0 cols array orig/span-> 023566b0 ***** start group cell map dump ***** 023565b0 maprowcount=0 tablerowcount=0 ***** end group cell map dump ***** ***** end table cell map dump ***** ***end table dump*** insertrowsafter ***start table dump*** mcolwidths=-1 -1 row(0)=02763344 cell(0)=02763528 cell(1)=0276381c row(1)=02763940 cell(0)=02763990 cell(1)=02763ab4 ***** start table cell map dump ***** 023566b...
...0 cols array orig/span-> 023566b00=2/0 1=2/0 ***** start group cell map dump ***** 023565b0 maprowcount=2 tablerowcount=2 row 0 : c0,0 c0,1 row 1 : c1,0 c1,1 c0,0=02763528(0) c0,1=0276381c(1) c1,0=02763990(0) c1,1=02763ab4(1) ***** end group cell map dump ***** ***** end table cell map dump ***** ***end table dump*** structural information one can imagine the cellmap as grid with equally wide rows and columns where the table cells are drawn.
How to implement a custom XUL query processor component - Archive of obsolete content
the component will hold a small array of javascript objects as its datasource.
... rulematched: function(aquery, arulenode) { }, // the output for a result has been removed and the result is no longer being used by the builder hasbeenremoved: function() { } }; // basic wrapper for nsisimpleenumerator function templateresultset(aarrayofdata) { this._index = 0; this._array = aarrayofdata; } templateresultset.prototype = { queryinterface: xpcomutils.generateqi([components.interfaces.nsisimpleenumerator]), hasmoreelements: function() { return this._index < this._array.length; }, getnext: function() { return new templateresult(this._array[this._index++]); } }; // the query processor class - implements ns...
Property Files - Archive of obsolete content
%s) is replaced by each successive element in the supplied array.
... you will notice the formatting codes %1$s and %2$s is used, and replaced different order in the array.
Using spell checking in XUL - Archive of obsolete content
nary); if (mpersonaldictionary.check("kat", gspellcheckengine.dictionary)) { // it's spelled correctly accourdly to user personal dictionary } else { // it's spelled incorrectly } } getting a list of suggestions to get a list of suggestions for a misspelled word, you call the suggest() method, specifying the word and an object to be filled with an array of possible suggestions.
... var suggestions = {}; gspellcheckengine.suggest("kat", suggestions, {}); if (suggestions.value) { // suggestions.value is a javascript array of strings // there were suggestions.value.length suggestions found } ...
XULBrowserWindow - Archive of obsolete content
method overview boolean hidechromeforlocation(in string alocation); attributes attribute type description incontentwhitelist string[] an array of url strings for which chrome is automatically hidden.
... defaults to about:addons but extensions can append specific urls to the array.
toolbox - Archive of obsolete content
the external toolbars associated with a toolbox are listed in the array of elements provided by the toolbox's externaltoolbars property.
... externaltoolbars type: array of elements an array of external toolbars; that is, toolbar elements that should be considered to be members of this toolbox, even if they are not actually children of the toolbox.
Enumerator - Archive of obsolete content
remarks collections differ from arrays in that the members of a collection are not directly accessible.
... instead of using indexes, as you would with arrays, you can move the current item pointer only to the first or next element of a collection.
New in JavaScript 1.6 - Archive of obsolete content
several new features were introduced: e4x, several new array methods, and array and string generics.
... array.prototype.indexof() array.prototype.lastindexof() array.prototype.every() array.prototype.filter() array.prototype.foreach() array.prototype.map() array.prototype.some() array generics string generics for each...in changed functionality in javascript 1.6 a bug in which arguments[n] cannot be set if n is greater than the number of formal or actual parameters has been fixed.
forEach - Archive of obsolete content
jswisher 01 october 2011 <hr> there is some mistype in array.prototype.foreach: kvalue = o[ pk ]; should be kvalue = o[ k ]; <hr> this page has been the target of a revert war, and so write access to it has been restricted.
...[1].foreach(function(value, index, array){ print(value); //break?
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
the variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered.
... javascript // using a string method doesn't mutate the string var bar = "baz"; console.log(bar); // baz bar.touppercase(); console.log(bar); // baz // using an array method mutates the array var foo = []; console.log(foo); // [] foo.push("plugh"); console.log(foo); // ["plugh"] // assignment gives the primitive a new (not a mutated) value bar = bar.touppercase(); // baz a primitive can be replaced, but it can't be directly altered.
JavaScript basics - Learn web development
let myvariable = true; array this is a structure that allows you to store multiple values in a single reference.
... let myvariable = [1,'bob','steve',10]; refer to each member of the array like this: myvariable[0], myvariable[1], etc.
Functions — reusable blocks of code - Learn web development
every time we manipulated a text string, for example: let mytext = 'i am a string'; let newstring = mytext.replace('string', 'sausage'); console.log(newstring); // the replace() string function takes a source string, // and a target string and replaces the source string, // with the target string, and returns the newly formed string or every time we manipulated an array: let myarray = ['i', 'love', 'chocolate', 'frogs']; let madeastring = myarray.join(' '); console.log(madeastring); // the join() function takes an array, joins // all the array items together into a single // string, and returns this new string or every time we generated a random number: let mynumber = math.random(); // the random() function generates a random number between // 0 and up to but...
...as an example, the array join() function's parameter is optional: let myarray = ['i', 'love', 'chocolate', 'frogs']; let madeastring = myarray.join(' '); // returns 'i love chocolate frogs' let madeastring = myarray.join(); // returns 'i,love,chocolate,frogs' if no parameter is included to specify a joining/delimiting character, a comma is used by default.
Test your skills: Functions - Learn web development
functions 1 for the first task, you have to create a simple function — choosename() — that prints a random name from the provided array (names) to the provided paragraph (para), and then run it once.
... update the choosename() function so that it makes use of the random number function, takes the array to choose from as a parameter (making it more flexible), and returns the result.
Test your skills: Loops - Learn web development
loops 1 in our first looping task we want you start by creating a simple loop that goes through all the items in the provided myarray and prints them out on the screen inside list items (i.e., <li> elements), which are appended to the provided list.
... loops 2 in this next task, we want you to write a simple program that, given a name, searches an array of objects containing names and phone numbers (phonebook) and, if it finds the name, outputs the name and phone number into the paragraph (para) and then exits the loop before it has run its course.
Third-party APIs - Learn web development
add the following code to your example, again inside window.onload: l.marker([53.480759, -2.242631], { icon: l.mapquest.icons.marker({ primarycolor: '#22407f', secondarycolor: '#3b5998', shadow: true, size: 'md', symbol: 'a' }) }) .bindpopup('this is manchester!') .addto(map); as you can see, this at its simplest takes two parameters, an array containing the coordinates at which to display the marker, and an options object containing an icon property that defines the icon to display at that point.
... next, we set the articles variable to equal json.response.docs — this is the array holding all the objects that represent the articles returned by the search.
What is JavaScript? - Learn web development
get references to all the buttons on the page in an array format.
...troubleshooting javascript storing the information you need — variables basic math in javascript — numbers and operators handling text — strings in javascript useful string methods arrays assessment: silly story generator ...
JavaScript — Dynamic client-side scripting - Learn web development
after that, we discuss some key javascript features in detail, such as variables, strings, numbers and arrays.
... introducing javascript objects in javascript, most things are objects, from core javascript features like strings and arrays to the browser apis built on top of javascript.
Ember interactivity: Events, classes and state - Learn web development
m '@ember/object'; update the existing export default class tododataservice extends service { … } block as follows: export default class tododataservice extends service { @tracked todos = []; @action add(text) { let newtodo = new todo(text); this.todos = [...this.todos, newtodo]; } } here, the todos property on the service will maintain our list of todos contained inside an array, and we'll mark it with @tracked, because when the value of todos is updated we want the ui to update as well.
...this function's contents are fairly easy to understand — when the function is invoked, a new todo object instance is created with a text value of text, and the todos property value is updated to all of the current items inside the array (accessed conveniently using spread syntax), plus the new todo.
Vue conditional rendering: editing existing todos - Learn web development
however, we haven’t actually handled updating the todoitems array back in app.vue.
... result: addtodo() method invoked to add new todo item to the todoitems array.
Creating our first Vue component - Learn web development
registering props in vue, there are two ways to register props: the first way is to just list props out as an array of strings.
... each entry in the array corresponds to the name of a prop.
Adding a new todo form: Vue events, methods, and models - Learn web development
adding the new todo into our data now that we have the data from todoform available in app.vue, we need to add an item representing it to the todoitems array.
... this can be done by pushing a new to-do item object to the array containing our new data.
Firefox and the "about" protocol
displays the status of the url classifier services that firefox uses (for example for safe browsing) about:webrtc information about webrtc usage about:welcome page first displayed when firefox is installed about:welcomeback information page displayed after firefox is reset these urls are defined in docshell/base/nsaboutredirector.cpp within the kredirmap array.
... the array maps most of the urls, like config to urls in the chrome: pseudo protocol, such as chrome://global/content/config.xul.
mozbrowsercontextmenu
systemtargets an array containing one or more menusystem objects (see the menusystem object, below), containing details of the standard menu(s) that will be shown.
... items an array of further menu objects, which indicate the menu options available in a menu, if the context menu being accessed is a menu.
HTTP Cache
the openers fifo is an array of cacheentry::callback objects.
... the memory pool is represented by two lists (strong refering ordered arrays) of cacheentry objects: sorted by expiration time (that default to 0xffffffff) sorted by frecency (defaults to 0) we have two such pools, one for memory-only entries actually representing the memory-only cache and one for disk cache entries for which we only keep the meta data.
Infallible memory allocation
p = moz_xmalloc(); p = moz_xcalloc(); p = moz_xrealloc(); p = moz_xstrdup(); f = new foo(); farray = new foo[]; n = ::operator new(...); narray = ::operator new[](...); explicitly fallible memory allocators these memory allocators are explicitly fallible, and will remain so.
... p = malloc(); p = realloc(); namespace mozilla { f = new (fallible) foo(); farray = new (fallible) foo[]; } namespace mozilla { n = ::operator new(..., fallible); narray = ::operator new[](..., fallible); } see also choosing the right memory allocator ns_alloc() ...
AddonUpdateChecker
updateinfo getcompatibilityupdate( in updateinfo updates[], in string version, in boolean ignorecompatibility, in string appversion, in string platformversion ) parameters updates an array of update objects version the version of the add-on to get new compatibility information for ignorecompatibility an optional parameter to get the first compatibility update that is compatible with any version of the application or toolkit appversion the version of the application or null to use the current version platformversion the version of the platform or null to use the current vers...
... updateinfo getnewestcompatibleupdate( in updateinfo updates[], in string appversion, in string platformversion ) parameters updates an array of update objects appversion the version of the application or null to use the current version platformversion the version of the platform or null to use the current version checkforupdates() starts an update check.
Add-on Manager
for example: components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getalladdons(function(aaddons) { // here aaddons is an array of addon objects }); // this code will execute before the code inside the callback notifications about changes to installed add-ons are dispatched to any registered addonlisteners.
... for example, to take a look at the add-ons that were disabled at startup: components.utils.import("resource://gre/modules/addonmanager.jsm"); let addonids = addonmanager.getstartupchanges(addonmanager.startup_change_disabled); if (addonids.length > 0) { // addonids is now an array of the add-on ids that have been disabled alert("note: " + addonids.length + " add-ons have been disabled."); } open add-on manager tab the add-on manager tab can be opened programatically with the function browseropenaddonsmgr which is available on chrome window of "navigator:browser" type.
Widget Wrappers
for xul-provided widgets, this is always 'custom' provider the provider type of the widget, id est one of provider_api or provider_xul instances an array of all instances (single window wrappers) of the widget.
... this array is not live.
PR_Poll
syntax #include <prio.h> print32 pr_poll( prpolldesc *pds, printn npds, printervaltime timeout); parameters the function has the following parameters: pds a pointer to the first element of an array of prpolldesc structures.
... npds the number of elements in the pds array.
PR_Writev
iov an array of priovec structures that describe the buffers to write from.
... size number of priovec structures in the iov array.
NSS 3.12.6 release notes
dcachewithopt ssl_settrustanchors ssl_getnegotiatedhostinfo new enum for sni: sslsninametype (see sslt.h) new functions in cert.h certdistnames: duplicate distinguished name array.
... cert_distnamesfromcertlist: generate an array of distinguished names from a list of certs.
NSS_3.12_release_notes.html
bug 417024: convert libpkix error code into nss error code bug 422859: libpkix builds & validates chain to root not in the caller-provided anchor list bug 425516: need to destroy data pointed by certvaloutparam array in case of error bug 426450: pkix_pl_hashtable_remove leaks hashtable key object bug 429230: memory leak in pkix_checkcert function bug 392696: fix copyright boilerplate in all new pkix code bug 300928: integrate libpkix to nss bug 303457: extensions newly supported in libpkix must be marked supported bug 331096: nss softoken must detect forks on all unix-ish platforms bug 390710: certnameconstra...
...979: vfychain ignores -b time option when -p option is present bug 403563: implement the tls session ticket extension (ste) bug 400917: want exported function that outputs all host names for dns name matching bug 315643: test_buildchain_resourcelimits won't build bug 353745: klocwork null ptr dereference in pkcs12 decoder bug 338367: the gf2m_populate and gfp_populate should check the eccurve_map array index bounds before use bug 201139: ssltap should display plain text for null cipher suites bug 233806: support nist crl policy bug 279085: nss tools display public exponent as negative number bug 363480: ocspclnt needs option to take cert from specified file bug 265715: remove unused hsearch.c dbm code bug 337361: leaks in jar_parse_any (security/nss/lib/jar/jarver.c) bug 338453: leaks in securi...
NSS 3.15 release notes
in secitem.h secitem_allocarray secitem_duparray secitem_freearray secitem_zfreearray - utility functions to handle the allocation and deallocation of secitemarrays secitem_reallocitemv2 - replaces secitem_reallocitem, which is now obsolete.
... new types in secitem.h secitemarray - represents a variable-length array of secitems.
FC_SetOperationState
poperationstate [in] pointer to a byte array containing the operation state.
... description fc_setoperationstate restores the cryptographic operations state of a session from an array of bytes obtained with fc_getoperationstate.
NSS functions
mxr 3.10 and later cert_decodeocspresponse mxr 3.6 and later cert_decodeoidsequence mxr 3.2 and later cert_decodeprivkeyusageperiodextension mxr 3.10 and later cert_decodetruststring mxr 3.4 and later cert_decodeusernotice mxr 3.2 and later cert_dernametoascii mxr 3.4 and later cert_destroycertarray mxr 3.2 and later cert_destroycertificate mxr 3.2 and later cert_destroycertificatelist mxr 3.2 and later cert_destroycertificatepoliciesextension mxr 3.2 and later cert_destroycertificaterequest mxr 3.2 and later cert_destroycertlist mxr 3.2 and later cert_destroyname mxr 3.2 and later cert_d...
... 3.2 and later pk11_getbestslotmultiple mxr 3.2 and later pk11_getbestwrapmechanism mxr 3.2 and later pk11_getblocksize mxr 3.2 and later pk11_getcertfromprivatekey mxr 3.9.3 and later pk11_getcurrentwrapindex mxr 3.2 and later pk11_getdefaultarray mxr 3.8 and later pk11_getdefaultflags mxr 3.8 and later pk11_getdisabledreason mxr 3.8 and later pk11_getfirstsafe mxr 3.2 and later pk11_getinternalkeyslot mxr 3.2 and later pk11_getinternalslot mxr 3.2 and later pk11_getkeygen ...
Creating JavaScript jstest reftests
non262 tests the directory js/src/tests/non262/ should contain all tests of the following type: regressions of spidermonkey non-standard spidermonkey extensions to the javascript language test of "implementation-defined" details of the ecmascript standard for example, the exact definition of pi or some details of array sorting.
... it is easy to make a test silently pass; anyone who has written js code for the web has written this kind of if-statement: if (typeof gc === 'function') { var arr = []; arr[10000] = 'item'; gc(); asserteq(arr[10000], 'item', 'gc must not wipe out sparse array elements'); } else { print('test skipped: no gc function'); } reportcompare(0, 0, 'ok'); handling abnormal test terminations some tests can terminate abnormally even though the test has technically passed.
Property cache
furthermore, y at t1 has the same number of fixed slots that x had at t0, and either both have a slot array or neither does.
...there are probably similar bugs to do with, for example, xml objects' custom getproperty op.) dense arrays are shapeless.
JSAPI Cookbook
creating an array // javascript var x = []; // or "x = array()", or "x = new array" /* jsapi */ js::rootedobject x(cx, js_newarrayobject(cx, 0)); if (!x) return false; creating an object // javascript var x = {}; // or "x = object()", or "x = new object" /* jsapi */ js::rootedobject x(cx, js_newplainobject(cx)); // or js_newobject(cx, js::nullptr(), js::nullptr(), js::nullptr()); if (!x) return f...
...*/ js::rootedstring name_str(cx, js_newstringcopyz(cx, "dave")); if (!name_str) return false; js::autovaluearray<2> args(cx); args[0].setstring(name_str); args[1].setint32(24); /* step 3 - call |new person(...args)|, passing the arguments.
JS::Construct
syntax bool js::construct(jscontext *cx, js::handlevalue fun, const js::handlevaluearray& args, js::mutablehandlevalue rval); name type description cx jscontext * pointer to a js context from which to derive runtime information.
... args js::handlevaluearray &amp; arguments you are passing to the function.
JS_AddArgumentFormatter
a pointer into an array of jsval values.
...for a given format string, for example "aa", the formatter is called from js_convertargumentsva like so: formatter(cx, "aa...", js_true, &sp, &ap); sp points into the arguments array on the js stack, while ap points into the stdarg.h va_list on the c stack.
JS_AliasElement
adding an alias element does not change the element array length.
...see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement bug 576034 ...
JS_DumpNamedRoots
rp void * a pointer to the rooted variable, array element, or field.
...it points to a variable, array element, or field of type jsval, jsobject *, jsstring *, or jsdouble *.
JS_EncodeCharacters
dst const char * the pointer to an array of bytes to be filled with encoded characters; or null.
... description js_encodecharacters copies the characters of a jschar array into a char array, converting the 16-bit values to 8-bit values.
JS_EnumerateResolvedStandardClasses
syntax jsidarray * js_enumerateresolvedstandardclasses(jscontext *cx, jsobject *obj, jsidarray *ida); name type description description js_enumerateresolvedstandardclasses enumerates any already-resolved standard class ids into ida, or into a new jsidarray if ida is null.
... return the augmented array on success, null on failure with ida (if it was non-null on entry) destroyed.
JS_HasElement
determine whether a javascript array has an element in the specified index.
... see also mxr id search for js_haselement js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement ...
JS_NewUCString
buf char * or char16_t * pointer to a character array, allocated with js_malloc, containing the characters for the js string to create.
...the character array, buf, must be allocated on the heap using js_malloc.
JS_NewStringCopyZ
s const char * or const char16_t * pointer to the character array containing the text for the js string to create; or null.
... description js_newstringcopyz allocates space for a new javascript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the new string.
JS_ReportErrorNumber
xt *cx, unsigned flags, jserrorcallback errorcallback, void *userref, const unsigned errornumber, ...); bool js_reporterrorflagsandnumberuc(jscontext *cx, unsigned flags, jserrorcallback errorcallback, void *userref, const unsigned errornumber, ...); void js_reporterrornumberucarray(jscontext *cx, jserrorcallback errorcallback, void *userref, const unsigned errornumber, const char16_t **args); // added in spidermonkey 19 name type description cx jscontext * the context in which to report the error.
...see also mxr id search for js_reporterrornumber mxr id search for js_reporterrornumberuc mxr id search for js_reporterrorflagsandnumber mxr id search for js_reporterrorflagsandnumberuc mxr id search for js_reporterrornumberucarray bug 801487 ...
JSDBGAPI
ect js_clearallwatchpoints inspecting the stack js_pctolinenumber js_linenumbertopc js_getfunctionscript js_getfunctionnative js_getfunctionfastnative js_getscriptprincipals typedef jsstackframe js_frameiterator js_getframescript js_getframepc js_getscriptedcaller js_stackframeprincipals js_evalframeprincipals js_getframeannotation js_setframeannotation js_getframeprincipalarray js_isnativeframe js_getframeobject js_getframescopechain js_getframecallobject js_getframethis js_getframefunction js_getframefunctionobject js_isconstructorframe js_isdebuggerframe js_getframereturnvalue js_setframereturnvalue js_getframecalleeobject js_getscriptfilename js_getscriptbaselinenumber js_getscriptlineextent js_getscriptversion js_gettopscriptfilenameflags j...
...s_getscriptfilenameflags js_flagscriptfilenameprefix jsfilename_null jsfilename_system jsfilename_protected evaluating debug code js_evaluateinstackframe examining object properties typedef jspropertydesc jspd_enumerate jspd_readonly jspd_permanent jspd_alias jspd_argument jspd_variable jspd_exception jspd_error typedef jspropertydescarray js_propertyiterator js_getpropertydesc js_getpropertydescarray js_putpropertydescarray hooks js_setdebuggerhandler js_setsourcehandler js_setexecutehook js_setcallhook js_setobjecthook js_setthrowhook js_setdebugerrorhook js_setnewscripthook js_setdestroyscripthook js_getglobaldebughooks js_setcontextdebughooks memory usage js_getobjecttotalsize js_getfunctiontotalsize js_getscripttotalsize sys...
TPS History Lists
an array of objects representing visits to the page, each object has the following properties: type: required.
...it's an array of objects, each of which represents a type of history to delete.
TPS Tests
a phase is defined by calling the phase function with the name of the phase and a list of actions to perform: phase('phase1', [ [bookmarks.add, bookmarks_initial], [passwords.add, passwords_initial], [history.add, history_initial], [sync, sync_wipe_server], ]); each action is an array, the first member of which is a function reference to call, the other members of which are parameters to pass to the function.
..., [ [sync], [bookmarks.verify, bookmarks_initial], [bookmarks.modify, bookmarks_initial], [bookmarks.verify, bookmarks_after_first_modify], [sync] ]); phase('phase3', [ [sync], [bookmarks.verify, bookmarks_after_first_modify] ]); the effects of this test file will be: firefox is launched with profile1, the tps extension adds the two bookmarks specified in the bookmarks_initial array, then they are synced to the sync server.
Web Replay
shared array buffers can be used by web content to introduce data races to the browser on the contents of those buffers, going against a fundamental assumption of the record/replay infrastructure.
... in general, redirections are needed for any function that is (a) not compiled as part of gecko, and either (b) may behave differently between recording and replaying, or (c) depends on data produced by other redirected functions (for example, corefoundation types like cfarrayref and cfstringref).
Using XPCOM Utilities to Make Things Easier
all of these macros work on an array of structures represented by the components parameter.
...modules such as the networking libraries in gecko ("necko") have over 50 components declared in a single nsmodulecomponentinfo array like this.
Mozilla internal string guide
each ascii value is stored in exactly one byte in the array with the most-significant 8th bit set to zero.
...because it was looked up from an array of literals of varying lengths), use assignascii().
Components.interfacesByID
components.interfacesbyid is a read-only array of classes indexed by iid.
... introduction components.interfacesbyid is a read-only array of objects which implement the nsijsiid interface.
Components.utils.importGlobalProperties
this function is passed an array of strings.
... syntax void components.utils.importglobalproperties([string1, string2, ...]); parameters [string1, string2, ...] an array of strings.
Components object
the components object has the following members: classes array of classes by contractid classesbyid array of classes by cid constructor constructor for constructor of components exception constructor for xpconnect exceptions id constructor for xpcom nsids interfaces array of interfaces by interface name interfacesbyid array of interfaces by iid issuccesscode function to determine if a given result code ...
...is a success code lastresult result code of most recent xpconnect call manager the global xpcom component manager results array of known result codes by name returncode pending result for current call stack current javascript call stack utils provides access to several useful features utils.atline provides access to the value of the atline property in the javascript environment.
BeginReading
const char_type* beginreading() const; remarks the resulting character array is not necessarily null-terminated.
... the length of the array is determined by the result of the length method.
BeginReading
const char_type* beginreading() const; remarks the resulting character array is not necessarily null-terminated.
... the length of the array is determined by the result of the length method.
XPCOM glue classes
this class is typically used to represent ascii or utf-8 character arrays.nsacstring (external)class declarationnsacstring_internalclass declarationnsadoptingcstringclass declarationnsadoptingstringclass declarationnsastringthe nsastring abstract class represents a character string composed of double-byte storage units.
... this class is typically used to represent unicode character arrays.nsastring (external)class declarationnsastring_internalclass declarationnsautorefnsautoref<t> is a template class implementing an object that holds a handle to a resource that must be released, typically on destruction of the object.</t>nsautoreftraitsnsautoreftraits<t> is a template class describing traits of resources held by objects of class nsautoref<t> and/or nscountedref<t>.</t>nsautostringclass declarationnsautostring (external)class declarationnscautostringclass declarationnscautostring (external)class declarationnscomptrthis utility class simplifies managing xpcom interface references from c++ code.nscountedrefnscountedref<t> is a template class implementing an object that takes a strong reference to a reference-counte...
amIWebInstallPrompt
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) method overview void confirm(in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, [optional] in pruint32 acount); prior to gecko 8.0, all references to nsidomwindow used in this interface were nsidomwindow.
...void confirm( in nsidomwindow awindow, in nsiuri auri, [array, size_is(acount)] in nsivariant ainstalls, in pruint32 acount optional ); parameters awindow the window that triggered the installs.
mozIPersonalDictionary
@mozilla.org/spellchecker/personaldictionary;1"] .getservice(components.interfaces.mozipersonaldictionary); method overview void addcorrection(in wstring word,in wstring correction, in wstring lang); void addword(in wstring word, in wstring lang); boolean check(in wstring word, in wstring lang); void endsession(); void getcorrection(in wstring word, [array, size_is(count)] out wstring words, out pruint32 count); void ignoreword(in wstring word); void load(); void removecorrection(in wstring word,in wstring correction, in wstring lang); void removeword(in wstring word, in wstring lang); void save(); attributes attribute type description wordlist nsistringenumerator get the (lexicographically sorted) list of words.
...void getcorrection( in wstring word, [array, size_is(count)] out wstring words, out pruint32 count ); parameters word the word to get the list of corrections for.
Children
« nsiaccessible page summary array of all this node's children.
... attribute nsiarray children; remark every child node in the array implements nsiaccessible interface.
GetKeyBindings
« nsiaccessible page summary this method provides array of localized string of global keyboard accelerator for the given action index supported by accessible.
...return values returns array of localized string of global keyboard accelerator.
nsIAccessible
layout oriented methods nsiaccessible.getchildatpoint() to get child accessible from point nsiaccessible.getaccessibletoleft(), nsiaccessible.getaccessibletoright(), nsiaccessible.getaccessibleabove() or nsiaccessible.getaccessiblebelow() to get left, right, top or below placed accessible methods getkeybindings provides array of localized string of global keyboard accelerator for the given action index supported by accessible.
... children array of all this element's children.
nsIAccessibleTableCell
columnheadercells nsiarray return an array of column header cells for this cell.
... rowheadercells nsiarray return an array of row header cells for this cell.
nsIApplicationCacheService
ally(in nsiapplicationcache cache, in acstring key); nsiapplicationcache chooseapplicationcache(in acstring key); nsiapplicationcache createapplicationcache(in acstring group); void deactivategroup(in acstring group); nsiapplicationcache getactivecache(in acstring group); nsiapplicationcache getapplicationcache(in acstring clientid); void getgroups([optional] out unsigned long count, [array, size_is(count), retval] out string groupids); methods cacheopportunistically() flags the specified key as one that should be cached opportunistically.
...void getgroups( out unsigned long count, optional [array, size_is(count), retval] out string groupids ); parameters count optional the count of the application cache groups.
nsIBlocklistPrompt
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void prompt([array, size_is(acount)] in nsivariant aaddons, [optional] in pruint32 acount); methods prompt() prompt the user about newly blocked addons.
...void prompt( [array, size_is(acount)] in nsivariant aaddons, in pruint32 acount optional ); parameters aaddons an array of addons and plugins that are blocked.
nsICommandLine
return value the position of the flag in the command line, or -1 if the flag is not found.getargument() gets the value an argument from the array of command-line arguments, given the index into the argument list.
... handleflag() finds the specified flag, removing it from the array of flags.
nsICookieService
depending on the data value, either an nsicookie2 interface pointer representing the cookie object that changed, or an nsiarray of nsicookie2 objects.
...the subject is an nsiarray of deleted cookies.
nsICryptoHMAC
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview acstring finish(in prbool aascii); void init(in unsigned long aalgorithm, in nsikeyobject akeyobject); void reset(); void update([const, array, size_is(alen)] in octet adata, in unsigned long alen); void updatefromstream(in nsiinputstream astream, in unsigned long alen); constants hashing algorithms.
...update() void update( [const, array, size_is(alen)] in octet adata, in unsigned long alen ); parameters adata a buffer to calculate the hash over.
nsIDOMHTMLAudioElement
unsigned long mozwriteaudio( in jsval data ); parameters data the samples to write into the audio stream, specified either as a javascript array or as a numeric typed array.
...ns_error_dom_type_mismatch_err the data isn't a valid data type (an array or typed array of numeric values).
nsIDOMXPathResult
snapshotlength unsigned long if resulttype is unordered_node_snapshot_type or ordered_node_snapshot_type, the length of the snapshort array.
...snapshotitem() returns the specified node from what is essentially an array of resulting dom nodes.
nsIDictionary
method overview boolean haskey(in string key); void getkeys(out pruint32 count, [retval, array, size_is(count)] out string keys); nsisupports getvalue(in string key); void setvalue(in string key, in nsisupports value); nsisupports deletevalue(in string key); void clear(); methods haskey() check if a given key is present in the dictionary.
... void getkeys( out pruint32 count, [retval, array, size_is(count)] out string keys ); return value array of all keys, unsorted.
nsIFeedEntry
enclosures nsiarray an array of all the enclosures included in the entry.
... mediacontent nsiarray an array of all the enclosures or other media that might be displayed inline in the entry.
nsIMessageListener
when there are multiple listeners to synchronous messages, each listener's return value is sent back as an element in an array.
... undefined return values show up as undefined values in the array.
nsIMsgAccount
inherits from: nsisupports last changed in gecko 1.7 method overview void addidentity(in nsimsgidentity identity); void clearallvalues(); void init(); void removeidentity(in nsimsgidentity identity); astring tostring(); attributes attribute type description defaultidentity nsimsgidentity identities nsisupportsarray read only.
... outgoing identity list (array of nsimsgidentity's) incomingserver nsimsgincomingserver incoming server stuff key acstring internal key identifying itself methods addidentity() adds a new identity to this account.
nsIMsgCompFields
properties attribute type description attachments char * obsolete attachments obsolete, do not use anymore attachmentsarray nsisupportsarray readonly attachvcard prbool bcc astring body astring bodyisasciionly prbool cc astring characterset char * defaultcharacterset char * readonly drafid char * dsn prbool fcc astring fcc2 astring followupto char * forcemsgencoding prbool forceplaintext ...
... astring templatename astring temporaryfiles char * obsolete temporaryfiles obsolete, do not use anymore to astring usemultipartalternative prbool uuencodeattachments prbool methods utility methods prbool checkcharsetconversion ( out char * fallbackcharset ); nsimsgrecipientarray splitrecipients ( in prunichar * recipients, in prbool emailaddressonly ); void convertbodytoplaintext ( ); attachment handling methods void addattachment ( in nsimsgattachment attachment ); void removeattachment ( in nsimsgattachment attachment ); void removeattachments ( ); header methods void setheader(char* name, char* value); ...
nsIMsgHeaderParser
astring makefulladdress(in astring aname, in astring aaddress); string makefulladdressstring(in string aname, in string aaddress); wstring makefulladdresswstring(in wstring name, in wstring addr); obsolete since gecko 1.9 void parseheaderaddresses(in string line, out string names, out string addresses, out pruint32 numaddresses); void parseheaderswitharray(in wstring aline, [array, size_is(count)] out wstring aemailaddresses, [array, size_is(count)] out wstring anames, [array, size_is(count)] out wstring afullnames, [retval] out unsigned long count); void reformatheaderaddresses(in string line, out string reformattedaddress); wstring reformatunquotedaddresses(in wstring line); void removeduplicateaddresses(in string addrs...
... exceptions thrown missing exception missing description parseheaderswitharray() void parseheaderswitharray( in wstring aline, [array, size_is(count)] out wstring aemailaddresses, [array, size_is(count)] out wstring anames, [array, size_is(count)] out wstring afullnames, [retval] out unsigned long count ); parameters aline the header line to parse.
nsIMsgMessageService
inherits from: nsisupports method overview void copymessage(in string asrcuri, in nsistreamlistener acopylistener, in boolean amovemessage, in nsiurllistener aurllistener, in nsimsgwindow amsgwindow, out nsiuri aurl); [noscript] void copymessages(in nsmsgkeyarrayptr keys, in nsimsgfolder srcfolder, in nsistreamlistener acopylistener, in boolean amovemessage, in nsiurllistener aurllistener, in nsimsgwindow amsgwindow, out nsiuri aurl); void displaymessage(in string amessageuri, in nsisupports adisplayconsumer, in nsimsgwindow amsgwindow, in nsiurllistener aurllistener, in string acharsetoverride, out nsiuri aurl); void openattachment(in s...
...see copymessage [noscript] void copymessages(in nsmsgkeyarrayptr keys, in nsimsgfolder srcfolder, in nsistreamlistener acopylistener, in boolean amovemessage, in nsiurllistener aurllistener, in nsimsgwindow amsgwindow, out nsiuri aurl); parameters keys an array of message ke...
nsIParentalControlsService
tal-controls-service;1"] .createinstance(components.interfaces.nsiparentalcontrolsservice); method overview void log(in short aentrytype, in boolean aflag, in nsiuri asource, [optional] in nsifile atarget); boolean requesturioverride(in nsiuri atarget, [optional] in nsiinterfacerequestor awindowcontext); boolean requesturioverrides(in nsiarray atargets, [optional] in nsiinterfacerequestor awindowcontext); attributes attribute type description blockfiledownloadsenabled boolean true if the current user account's parental controls restrictions include the blocking of all file downloads.
... boolean requesturioverrides( in nsiarray atargets, in nsiinterfacerequestor awindowcontext optional ); parameters atargets an array of nsiuri objects, each representing a uri for which an override is desired.
nsIPluginHost
void getplugintags([optional] out unsigned long aplugincount, [retval, array, size_is(aplugincount)] out nsiplugintag aresults); void handlebadplugin(in prlibraryptr alibrary, in nsiplugininstance instance); native code only!
... getplugintags() void getplugintags( out unsigned long aplugincount, optional [retval, array, size_is(aplugincount)] out nsiplugintag aresults ); parameters aplugincount optional aresults native code only!handlebadplugin void handlebadplugin( in prlibraryptr alibrary, in nsiplugininstance instance ); parameters alibrary instance native code only!init void init(); parameters none.
nsIRandomGenerator
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void generaterandombytes(in unsigned long alength, [retval, array, size_is(alength)] out octet abuffer); methods generaterandombytes() generates the specified amount of random bytes.
... void generaterandombytes( in unsigned long alength, [retval, array, size_is(alength)] out octet abuffer ); parameters alength the length of the data to generate.
nsITaskbarWindowPreview
the array of buttons may be accessed by calling getbutton(); each button is an nsitaskbarpreviewbutton object.
...nsitaskbarpreviewbutton getbutton( in unsigned long index ); parameters index the index into the button array for the nsitaskbarpreviewbutton to retrieve.
nsIWindowWatcher
an nsisupportsarray will be unwound into multiple arguments (but not recursively!).
...as of gecko 1.9 alpha 1, can also be an nsiarray instead.
nsIXMLHttpRequest
.status + ']'); break; } }; let evf = f => ['load', 'error', 'abort'].foreach(f); evf(m => xhr.addeventlistener(m, handler, false)); xhr.mozbackgroundrequest = true; xhr.open('get', url, true); xhr.channel.loadflags |= ci.nsirequest.load_anonymous | ci.nsirequest.load_bypass_cache | ci.nsirequest.inhibit_persistent_caching; xhr.responsetype = "arraybuffer"; //dont set it, so it returns string, you dont want arraybuffer.
... you only want this if your url is to a zip file or some file you want to download and make a nsiarraybufferinputstream out of it or something xhr.send(null); } xhr('https://www.gravatar.com/avatar/eb9895ade1bd6627e054429d1e18b576?s=24&d=identicon&r=pg&f=1', data => { services.prompt.alert(null, 'xhr success', data); var file = os.path.join(os.constants.path.desktopdir, "test.png"); var promised = os.file.writeatomic(file, new uint8array(data)); promised.then( function() { alert('succesfully saved image to desktop') }, function(ex) { alert('failed in saving image to desktop') } ); }); ...
XPCOM tasks
p2 classes that parallel standard library classes should have compatible apis, i.e., nsdeque bug 18505 nsstring nsavltree nshashtable our various array classes in some cases, this might initially be provided by additional interfaces.
... 5.1 should we provide type-safe templatized containers, e.g., over nsisupportsarray?
xptcall FAQ
the information in the typelibs allows xpconnect to convert function parameters and build the nsxptcvariant array required to make this call.
...these stubs forward calls to a shared function whose job it is to use the typelib information to extract the parameters from the platform specific calling convention to build an array of variants to hold the parameters and then call an inherited method which can then do whatever it wants with the call.
Xptcall Porting Guide
the invoke functionality requires the implementation of the following on each platform (from xptcall/public/xptcall.h): xptc_public_api(nsresult) ns_invokebyindex(nsisupports* that, pruint32 methodindex, pruint32 paramcount, nsxptcvariant* params); calling code is expected to supply an array of nsxptcvariant structs.
...the stubs forward calls to a platform specific method that uses the interface information supplied by the overridden getinterfaceinfo to extract the parameters and build an array of platform independent nsxptcminivariant structs which are in turn passed on to the overridden callmethod.
MailNews fakeserver
erver xpcshell api </caption> name arguments returns description performtest none nothing runs until the test is forcibly aborted or stopped normally isstopped none if the server is stopped helper for performtest istestfinished none if the test is finished helper for performtest playtransaction none the transaction the transaction is an object with two properties: us, and them; us is an array of responses we sent, them an array of commands received resettest none nothing prepares the server for the next test without closing the connection start port number nothing starts the server listening stop none nothing stops the server and closes the connection using fakeserver in qa testing debug output from fakeservers it is possible to get the fakeservers to dump to the console ...
...g adds the group (resetting if it exists) addarticle newsarticle object nothing adds the message to all groups in the article's group list addarticletogroup newsarticle object, group (string), integral key for group nothing adds the message to the specified group with the specified key getgroup group name group object group is a map key->article, with the additional properties: flags, keys (array of keys), nextkey (next key to use for new articles) getgroupstats group name array of [size, min, max] the size is an estimate if nntp_real_length is not specified in the daemon flags.
Using C struct and pointers
the second parameter is an array of field descriptors.
...additionally, the js-ctypes pointer must be casted to reflect the size of the buffer: var ptr = ctypes.cast( str, ctypes.arraytype( ctypes.char, buff_size ).ptr ); here buff_size is of type ctypes.size_t.
Using Objective-C from js-ctypes
tancetype)initwithcstring:(const char *)nullterminatedcstring encoding:(nsstringencoding)encoding and nsstringencoding is defined as: typedef unsigned long nsuinteger; typedef nsuinteger nsstringencoding; so, our function call can be converted into the following js-ctypes code: let text = objc_msgsend(tmp2, initwithcstring_encoding, ctypes.char.array()("hello, firefox!"), ctypes.unsigned_long(nsutf8stringencoding)); converted js-ctypes code finally, we have our converted code.
... = objc_msgsend(nsspeechsynthesizer, alloc); let synth = objc_msgsend(tmp, initwithvoice, ctypes.voidptr_t(null)); let nsstring = objc_getclass("nsstring"); let initwithcstring_encoding = sel_registername("initwithcstring:encoding:"); let nsutf8stringencoding = 4; let tmp2 = objc_msgsend(nsstring, alloc); let text = objc_msgsend(tmp2, initwithcstring_encoding, ctypes.char.array()("hello, firefox!"), ctypes.unsigned_long(nsutf8stringencoding)); let startspeakingstring = sel_registername("startspeakingstring:"); objc_msgsend(synth, startspeakingstring, text); let isspeaking = sel_registername("isspeaking"); // wait until start speaking.
Memory Management
memory management if js code creates a structure or an array, that memory will be valid as long as the js object stays alive.
...for example, a cdata object produced by accessing a field of a structure or the internals of an array will hold the referent objects alive.
Initialization and Destruction - Plugins
it determines the number of attributes in the arrays specified by the argn and argv parameters.
...the argn array contains the attribute names; the argv array contains the attribute values.
Tree map view - Firefox Developer Tools
for the treemaps shown in the memory tool, things on the heap are divided at the top level into four categories: objects: javascript and dom objects, such as function, object, or array, and dom types like window and htmldivelement.
... this treemap is from the monster allocation example, which creates three arrays, each containing 5000 monsters, each monster having a randomly-generated name.
AddressErrors.addressLine - Web APIs
an object based on addresserrors includes an addressline property when validation of the address finds one or more errors in the array of strings in the address's addressline.
... syntax var addresslineerror = addresserrors.addressline; value if an error occurred during validation of the address due to one of the strings in the addressline array having an invalid value, this property is set to a domstring providing a human-readable error message explaining the validation error.
AnalyserNode.fftSize - Web APIs
analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount ; var dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.linewidth = 2; canvasctx.strokes...
...tyle = 'rgb(0, 0, 0)'; canvasctx.beginpath(); var slicewidth = width * 1.0 / bufferlength; var x = 0; for(var i = 0; i < bufferlength; i++) { var v = dataarray[i] / 128.0; var y = v * height/2; if(i === 0) { canvasctx.moveto(x, y); } else { canvasctx.lineto(x, y); } x += slicewidth; } canvasctx.lineto(canvas.width, canvas.height/2); canvasctx.stroke(); }; draw(); specifications specification status comment web audio apithe definition of 'fftsize' in that specification.
AnalyserNode.maxDecibels - Web APIs
analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheig...
...ht = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,barwidth,barheight/2); x += barwidth + 1; } }; draw(); specifications specification status comment web audio apithe definition of 'maxdecibels' in that specification.
AnalyserNode.minDecibels - Web APIs
analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheig...
...ht = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,barwidth,barheight/2); x += barwidth + 1; } }; draw(); specifications specification status comment web audio apithe definition of 'mindecibels' in that specification.
AnalyserNode.smoothingTimeConstant - Web APIs
analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheig...
...ht = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,barwidth,barheight/2); x += barwidth + 1; } }; draw(); specifications specification status comment web audio apithe definition of 'smoothingtimeconstant' in that specification.
AudioBuffer.duration - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); myarraybuffer.duration; value a double.
... example // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < framecount; i++) { // math.random() is in [0; 1.0] // audio needs to be in [-1.0; 1.0] nowbuffering[i] = math.random() * 2 - 1; } } console.log(myarraybuffer.duration); } specification specifi...
AudioBuffer.length - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); myarraybuffer.length; value an integer.
... example // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < framecount; i++) { // math.random() is in [0; 1.0] // audio needs to be in [-1.0; 1.0] nowbuffering[i] = math.random() * 2 - 1; } } console.log(myarraybuffer.length); } specification specificat...
AudioBuffer.numberOfChannels - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); myarraybuffer.numberofchannels; value an integer.
... example // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < framecount; i++) { // math.random() is in [0; 1.0] // audio needs to be in [-1.0; 1.0] nowbuffering[i] = math.random() * 2 - 1; } } console.log(myarraybuffer.numberofchannels); } specification ...
AudioBuffer.sampleRate - Web APIs
syntax var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); myarraybuffer.samplerate; value a floating-point value indicating the current sample rate of the buffers data, in samples per second.
... example // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < framecount; i++) { // math.random() is in [0; 1.0] // audio needs to be in [-1.0; 1.0] nowbuffering[i] = math.random() * 2 - 1; } } console.log(myarraybuffer.samplerate); } specification specif...
AudioBufferSourceNode.buffer - Web APIs
var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; //just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < framecount;...
... // this is the audionode to use when we want to play an audiobuffer var source = audioctx.createbuffersource(); // set the buffer in the audiobuffersourcenode source.buffer = myarraybuffer; specifications specification status comment web audio apithe definition of 'buffer' in that specification.
AudioBufferSourceNode - Web APIs
var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create an empty three-second stereo buffer at the sample rate of the audiocontext var myarraybuffer = audioctx.createbuffer(2, audioctx.samplerate * 3, audioctx.samplerate); // fill the buffer with white noise; //just random values between -1.0 and 1.0 for (var channel = 0; channel < myarraybuffer.numberofchannels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < myarraybuffer.l...
...// this is the audionode to use when we want to play an audiobuffer var source = audioctx.createbuffersource(); // set the buffer in the audiobuffersourcenode source.buffer = myarraybuffer; // connect the audiobuffersourcenode to the // destination so we can hear the sound source.connect(audioctx.destination); // start the source playing source.start(); for a decodeaudiodata() example, see the audiocontext.decodeaudiodata() page.
AudioParamDescriptor - Web APIs
if the underlying audioworkletprocessor has a parameterdescriptors static getter, then the returned array of objects based on this dictionary is used internally by audioworkletnode constructor to populate its parameters property accordingly.
...parameters['customgain'][i] : parameters['customgain'][0]) // note: a parameter contains an array of 128 values (one value for each of 128 samples), // however it may contain a single value which is to be used for all 128 samples // if no automation is scheduled for the moment.
AudioTrack.label - Web APIs
WebAPIAudioTracklabel
example this example returns an array of track kinds and labels for potential use in a user interface to select audio tracks for a specified media element.
...acklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "main-desc", "translation", "commentary" ]; el.audiotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); return tracklist; } the resulting tracklist contains an array of audio tracks whose kind is one of those in the array wantedkinds, with each entry providing the track's id, kind, and label.
AudioWorkletProcessor() - Web APIs
outputchannelcount optional an array defining the number of channels for each output.
...the array length must match numberofoutputs.
AuthenticatorResponse - Web APIs
authenticatorassertionresponse authenticatorattestationresponse properties authenticatorresponse.clientdatajson a json string in an arraybuffer, representing the client data that was passed to credentialscontainer.create() or credentialscontainer.get().
... examples getting an authenticatorassertionresponse var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { var assertionresponse = credentialinfoassertion.response; // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); getting an authenticatorattestationresponse var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", ...
Background Tasks API - Web APIs
variable declarations let tasklist = []; let totaltaskcount = 0; let currenttasknumber = 0; let taskhandle = null; these variables are used to manage the list of tasks that are waiting to be performed, as well as status information about the task queue and its execution: tasklist is an array of objects, each representing one task waiting to be run.
... to enqueue the task, we push an object onto the tasklist array; the object contains the taskhandler and taskdata values under the names handler and data, respectively, then increment totaltaskcount, which reflects the total number of tasks which have ever been enqueued (we don't decrement it when tasks are removed from the queue).
BaseAudioContext.createAnalyser() - Web APIs
analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.linewidth = 2; canvasctx.strokes...
...tyle = 'rgb(0, 0, 0)'; canvasctx.beginpath(); var slicewidth = width * 1.0 / bufferlength; var x = 0; for(var i = 0; i < bufferlength; i++) { var v = dataarray[i] / 128.0; var y = v * height/2; if(i === 0) { canvasctx.moveto(x, y); } else { canvasctx.lineto(x, y); } x += slicewidth; } canvasctx.lineto(canvas.width, canvas.height/2); canvasctx.stroke(); }; draw(); specifications specification status comment web audio apithe definition of 'createanalyser()' in that specification.
BaseAudioContext.createBuffer() - Web APIs
var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create an empty three-second stereo buffer at the sample rate of the audiocontext var myarraybuffer = audioctx.createbuffer(2, audioctx.samplerate * 3, audioctx.samplerate); // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < myarraybuffer.numberofchannels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < myarraybuffer.
...// this is the audionode to use when we want to play an audiobuffer var source = audioctx.createbuffersource(); // set the buffer in the audiobuffersourcenode source.buffer = myarraybuffer; // connect the audiobuffersourcenode to the // destination so we can hear the sound source.connect(audioctx.destination); // start the source playing source.start(); specifications specification status comment web audio apithe definition of 'createbuffer()' in that specification.
BaseAudioContext.createBufferSource() - Web APIs
= new (window.audiocontext || window.webkitaudiocontext)(); var button = document.queryselector('button'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); button.onclick = function() { // fill the buffer with white noise; //just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { // this gives us the actual arraybuffer that contains the data var nowbuffering = myarraybuffer.getchanneldata(channel); for (var i = 0; i < framecount;...
... // this is the audionode to use when we want to play an audiobuffer var source = audioctx.createbuffersource(); // set the buffer in the audiobuffersourcenode source.buffer = myarraybuffer; // connect the audiobuffersourcenode to the // destination so we can hear the sound source.connect(audioctx.destination); // start the source playing source.start(); } specifications specification status comment web audio apithe definition of 'createbuffersource()' in that specification.
BaseAudioContext - Web APIs
baseaudiocontext.decodeaudiodata() asynchronously decodes audio file data contained in an arraybuffer.
... in this case, the arraybuffer is usually loaded from an xmlhttprequest's response attribute after setting the responsetype to arraybuffer.
BasicCardRequest.supportedNetworks - Web APIs
the supportednetworks property of the basiccardrequest dictionary contains an array of domstrings representing the card networks that the retailer supports (e.g.
...value]] value an array containing one or more domstrings, which describe the card networks the retailer supports.
BasicCardRequest.supportedTypes - Web APIs
the obsolete supportedtypes property of the basiccardrequest dictionary can optionally be provided to specify an array of domstrings representing the card types that the retailer supports (e.g.
... syntax basiccardrequest.supportedtypes = [cardtype1...cardtypen]; value an array containing one or more domstrings, which describe the card types the retailer supports.
BasicCardRequest - Web APIs
properties basiccardrequest.supportednetworks optional secure context an optional array of domstrings representing the card networks that the retailer supports (e.g.
... basiccardrequest.supportedtypes optional secure context this obsolete property was used to provide an optional array of domstrings representing the card types that the retailer supports (e.g.
Beacon API - Web APIs
the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata.
...the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata.
BluetoothAdvertisingData - Web APIs
bluetoothadvertisingdata.manufacturerdata read only returns a map that relates company identifier codes to arraybuffers.
... bluetoothadvertisingdata.servicedata read only returns a map that relates uuids to arraybuffers.
BluetoothRemoteGATTCharacteristic.getDescriptors() - Web APIs
the bluetoothremotegattcharacteristic.getdescriptors() method returns a promise that resolves to an array of all bluetoothgattdescriptor objects for a given descriptor uuid.
...}) returns a promise that resolves to an array of bluetoothgattdescriptor objects.
BluetoothRemoteGATTCharacteristic.writeValue() - Web APIs
the bluetoothremotegattcharacteristic.writevalue() method sets the value property to the bytes contained in an arraybuffer and returns a promise.
... parameters value an arraybuffer.
readValue() - Web APIs
the bluetoothremotegattdescriptor.readvalue() method returns a promise that resolves to an arraybuffer holding a duplicate of the value property if it is available and supported.
...}) returns a promise that resolves to an arraybuffer.
value - Web APIs
the bluetoothremotegattdescriptor.value read-only property returns an arraybuffer containing the currently cached descriptor value.
... syntax var characteristic = bluetoothremotegattdescriptor.characteristic returns an arraybuffer.
BluetoothRemoteGATTService - Web APIs
bluetoothremotegattservice.getcharacteristics() returns a promise to an array of bluetoothgattcharacteristic instances for an optional universally unique identifier (uuid).
... bluetoothremotegattservice.getincludedservices() returns a promise to an array of bluetoothremotegattservice instances for an optional universally unique identifier (uuid).
Body - Web APIs
WebAPIBody
methods body.arraybuffer() takes a response stream and reads it to completion.
... it returns a promise that resolves with an arraybuffer.
CSSMathProduct.values - Web APIs
the cssmathproduct.values read-only property of the cssmathproduct interface returns a cssnumericarray object which contains one or more cssnumericvalue objects.
... syntax var cssnumericarray = cssmathproduct.values; value a cssnumericarray.
CSSMathSum.values - Web APIs
WebAPICSSMathSumvalues
the cssmathsum.values read-only property of the cssmathsum interface returns a cssnumericarray object which contains one or more cssnumericvalue objects.
... syntax var cssnumericarray = cssmathsum.values; value a cssnumericarray.
CSSMathSum - Web APIs
properties cssmathsum.values returns a cssnumericarray object which contains one or more cssnumericvalue objects.
... <div>has width</div> we assign a width div { width: calc(30% - 20px); } we add the javascript const stylemap = document.queryselector('div').computedstylemap(); console.log( stylemap.get('width') ); // cssmathsum {values: cssnumericarray, operator: "sum"} console.log( stylemap.get('width').operator ); // 'sum' console.log( stylemap.get('width').values ); // cssnumericarray {0: cssunitvalue, 1: cssunitvalue, length: 2} console.log( stylemap.get('width').values[0] ); // cssunitvalue {value: 30, unit: "percent"} console.log( stylemap.get('width').values[0].value ); // 30 console.log( stylemap.get('width').v...
CSSStyleValue.parseAll() - Web APIs
the parseall() method of the cssstylevalue interface sets all occurences of a specific css property to the specified value and returns an array of cssstylevalue objects, each containing one of the supplied values.
... return value an array of cssstylevalue objects, each containing one of the supplied values.
CSSUnparsedValue.entries() - Web APIs
the cssunparsedvalue.entries() method returns an array of a given object's own enumerable property [key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
... return value an array of the given cssunparsedvalue object's own enumerable property [key, value] pairs.
CSSUnparsedValue.forEach() - Web APIs
syntax cssunparsedvalue.foreach(function callback(currentvalue[, index[, array]]) { // your iterator }[, thisarg]); parameters callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed.
... arrayoptional the cssunparsedvalue that foreach() is being called on.
CSSUnparsedValue.keys() - Web APIs
the cssunparsedvalue.keys() method returns a new array iterator object that contains the keys for each index in the array.
... return value a new array.
CSSUnparsedValue.values() - Web APIs
the cssunparsedvalue.values() method returns a new array iterator object that contains the values for each index in the cssunparsedvalue object.
... return value a new array.
Cache.addAll() - Web APIs
WebAPICacheaddAll
the addall() method of the cache interface takes an array of urls, retrieves them, and adds the resulting response objects to the given cache.
... syntax cache.addall(requests[]).then(function() { // requests have been added to the cache }); parameters requests an array of string urls that you want to be fetched and added to the cache.
CacheStorage.delete() - Web APIs
here we have an array of cache names we want to keep (cachestokeep).
... we return the keys of the caches in the cachestorage object using cachestorage.keys, then check each key to see if it is in the array.
CacheStorage.keys() - Web APIs
WebAPICacheStoragekeys
the keys() method of the cachestorage interface returns a promise that will resolve with an array containing strings corresponding to all of the named cache objects tracked by the cachestorage object in the order they were created.
... return value a promise that resolves with an array of the cache names inside the cachestorage object.
CacheStorage - Web APIs
equivalent functionality to match a cache entry can be implemented by returning an array of cache names from cachestorage.keys(), opening each cache with cachestorage.open(), and matching the one you want with cache.match().
... cachestorage.keys() returns a promise that will resolve with an array containing strings corresponding to all of the named cache objects tracked by the cachestorage.
CanvasRenderingContext2D.getLineDash() - Web APIs
syntax ctx.getlinedash(); return value an array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units).
... if the number, when setting the elements, is odd, the elements of the array get copied and concatenated.
CanvasRenderingContext2D.putImageData() - Web APIs
syntax void ctx.putimagedata(imagedata, dx, dy); void ctx.putimagedata(imagedata, dx, dy, dirtyx, dirtyy, dirtywidth, dirtyheight); parameters imagedata an imagedata object containing the array of pixel values.
..., 0, canvas.width, canvas.height); const pixels = imgdata.data; pixels[0 + 0] = 1; pixels[0 + 1] = 127; pixels[0 + 2] = 255; pixels[0 + 3] = 1; console.log("before:", pixels); context.putimagedata(imgdata, 0, 0); const imgdata2 = context.getimagedata(0, 0, canvas.width, canvas.height); const pixels2 = imgdata2.data; console.log("after:", pixels2); the output might look like: before: uint8clampedarray(4) [ 1, 127, 255, 1 ] after: uint8clampedarray(4) [ 255, 255, 255, 1 ] specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.putimagedata' in that specification.
CanvasRenderingContext2D - Web APIs
canvasrenderingcontext2d.getlinedash() returns the current line dash pattern array containing an even number of non-negative numbers.
... canvasrenderingcontext2d.linedashoffset specifies where to start a dash array on a line.
Applying styles and colors - Web APIs
getlinedash() returns the current line dash pattern array containing an even number of non-negative numbers.
... linedashoffset = value specifies where to start a dash array on a line.
ConstrainDOMString - Web APIs
you can also specify a single string (or an array of strings) which the user agent will do its best to match once all more stringent constraints have been applied.
... properties the value of a constraindomstring can be any of the following: a single domstring an array of domstring objects an object with one or both of the following properties: exact either a single domstring which must be the value of the property, or an array of domstring objects one of which must be the property's value.
CredentialsContainer.get() - Web APIs
the available options are: providers: an array of domstring instances of identity providers to search for.
... protocols an array of domstring instances of federation protocols to search for.
CryptoKey - Web APIs
WebAPICryptoKey
cryptokey.usages an array of strings, indicating what can be done with the key.
... possible values for array elements are: "encrypt": the key may be used to encrypt messages.
Binary strings - Web APIs
WebAPIDOMStringBinary
javascript typed arrays provide a mechanism for accessing raw binary data much more efficiently.
... the stringview non native constructor is one level above typed arrays and provides a c-like interface for strings.
DataTransfer.types - Web APIs
the datatransfer.types read-only property returns an array of the drag data formats (as strings) that were set in the dragstart event.
... syntax datatransfer.types; return value an array of the data formats used in the drag operation.
Document - Web APIs
WebAPIDocument
document.getanimations() returns an array of all animation objects currently in effect, whose target elements are descendants of the document.
... documentorshadowroot.elementsfrompoint() returns an array of all elements at the specified coordinates.
DocumentOrShadowRoot.elementsFromPoint() - Web APIs
the elementsfrompoint() method of the documentorshadowroot interface returns an array of all elements at the specified coordinates (relative to the viewport).
... return value an array of element objects.
DocumentOrShadowRoot.nodesFromPoint() - Web APIs
the nodesfrompoint() property of the documentorshadowroot interface returns an array of all nodes at the specified coordinates (relative to the viewport).
... returns an array of node objects.
DocumentOrShadowRoot - Web APIs
documentorshadowroot.elementsfrompoint() returns an array of all elements at the specified coordinates.
... documentorshadowroot.nodesfrompoint() returns an array of all nodes at the specified coordinates.
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
when called, it returns an array with all of the element's descendants matching the tag name.
... the first element of the list is located at position [0] in the array.
EXT_float_blend - Web APIs
with this extension enabled, calling drawarrays() or drawelements() with blending enabled and a draw buffer with 32-bit floating-point components will no longer result in an invalid_operation error.
...t_blend'); const tex = gl.createtexture(); gl.bindtexture(gl.texture_2d, tex); // use floating point format gl.teximage2d(gl.texture_2d, 0, gl.rgba32f, 1, 1, 0, gl.rgba, gl.float, null); const fb = gl.createframebuffer(); gl.bindframebuffer(gl.framebuffer, fb); gl.framebuffertexture2d(gl.framebuffer, gl.color_attachment0, gl.texture_2d, tex, 0); // enable blending gl.enable(gl.blend); gl.drawarrays(gl.points, 0, 1); // won't throw gl.invalid_operation with the extension enabled specifications specification status ext_float_blend draft ...
Element.animate() - Web APIs
WebAPIElementanimate
syntax var animation = element.animate(keyframes, options); parameters keyframes either an array of keyframe objects, or a keyframe object whose property are arrays of values to iterate over.
...notice the array of objects passed as keyframes and also the timing options block.
Element - Web APIs
WebAPIElement
element.getanimations() returns an array of animation objects currently active on the element.
... element.getattributenames() returns an array of attribute names from the current element.
Using files from web applications - Web APIs
you can determine how many files the user selected by checking the value of the file list's length attribute: const numfiles = filelist.length; individual file objects can be retrieved by simply accessing the list as an array: for (let i = 0, numfiles = filelist.length; i < numfiles; i++) { const file = filelist[i]; // ...
...n() { const dropzone = document.getelementbyid("dropzone"); dropzone.ondragover = dropzone.ondragenter = function(event) { event.stoppropagation(); event.preventdefault(); } dropzone.ondrop = function(event) { event.stoppropagation(); event.preventdefault(); const filesarray = event.datatransfer.files; for (let i=0; i<filesarray.length; i++) { sendfile(filesarray[i]); } } } </script> </head> <body> <div> <div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">drag & drop your file here...</div> </div> </body> </html> example: using object u...
File - Web APIs
WebAPIFile
blob.prototype.arraybuffer() transforms the file into a stream and reads it to completion.
... it returns a promise that resolves with an arraybuffer.
FileReader.result - Web APIs
WebAPIFileReaderresult
syntax var file = instanceoffilereader.result value an appropiate string or arraybuffer based on which of the reading methods was used to initiate the read operation.
... method description readasarraybuffer() the result is a javascript arraybuffer containing binary data.
FileSystemDirectoryReader - Web APIs
methods readentries() returns an array containing some number of the directory's entries.
... each item in the array is an object based on filesystementry—typically either filesystemfileentry or filesystemdirectoryentry.
FileHandle API - Web APIs
the lockedfile interface provides a readastext method and a readasarraybuffer method.
... var progress = document.queryselector('progress'); var myfile = myfilehandle.open('readonly'); // let's read a 1gb file var action = myfile.readasarraybuffer(1000000000); action.onprogress = function (event) { if (progress) { progress.value = event.loaded; progress.max = event.total; } } action.onsuccess = function () { console.log('yeah \o/ just read a 1gb file'); } action.onerror = function () { console.log('oups :( unable to read a 1gb file') } file storage when a file handle is created, the associated file only exists...
FontFaceSetLoadEvent.fontfaces - Web APIs
the fontfaces read-only property of the fontfaceloadeventinit interface returns an array of fontface instances, each of which represents a single usable font.
... syntax var fontface[] = fontfacesetloadevent.fontfaces value an array of fontface instance.
FormData.getAll() - Web APIs
WebAPIFormDatagetAll
returns an array of formdataentryvalues whose key matches the value passed in the name parameter.
... example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following getall() function will return both username values in an array: formdata.getall('username'); // returns ["chris", "bob"] specifications specification status comment xmlhttprequestthe definition of 'getall()' in that specification.
Gamepad.hapticActuators - Web APIs
the hapticactuators read-only property of the gamepad interface returns an array containing gamepadhapticactuator objects, each of which represents haptic feedback hardware available on the controller.
... syntax var myhapticactuators = gamepadinstance.hapticactuators; value an array containing gamepadhapticactuator objects.
HTMLCanvasElement.toBlob() - Web APIs
var canvas = document.getelementbyid('canvas'); var d = canvas.width; ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(d / 2, 0); ctx.lineto(d, d); ctx.lineto(0, d); ctx.closepath(); ctx.fillstyle = 'yellow'; ctx.fill(); function blobcallback(iconname) { return function(b) { var r = new filereader(); r.onloadend = function () { // r.result contains the arraybuffer.
... cu.import('resource://gre/modules/osfile.jsm'); var writepath = os.path.join(os.constants.path.desktopdir, iconname + '.ico'); var promise = os.file.writeatomic(writepath, new uint8array(r.result), {tmppath:writepath + '.tmp'}); promise.then( function() { console.log('successfully wrote file'); }, function() { console.log('failure writing file') } ); }; r.readasarraybuffer(b); } } canvas.toblob(blobcallback('passthisstring'), 'image/vnd.microsoft.icon', '-moz-parse-options:format=bmp;bpp=32'); specifications specification status comment html living standardthe definition of 'htmlcanvaselement.toblob' in that specificat...
HTMLCollection - Web APIs
the htmlcollection interface represents a generic collection (array-like object similar to arguments) of elements (in document order) and offers methods and properties for selecting from the list.
...currently htmlcollections does not recognize purely numeric ids, which would cause conflict with the array-style access, though html5 does permit these.
HTMLFormElement - Web APIs
document.forms returns an array of htmlformelement objects listing each of the forms on the page.
... you can then use any of the following syntaxes to get an individual form: document.forms[index] returns the form at the specified index into the array of forms.
HTMLSelectElement - Web APIs
you can also access an item by specifying the index in array-style brackets or parentheses, without calling this method explicitly.
...you can also access an item by specifying the name in array-style brackets or parentheses, without calling this method explicitly.
The HTML DOM API - Web APIs
barprop navigator window deprecated web app and browser integration interfaces external obsolete web app and browser integration interfaces applicationcache plugin pluginarray form support interfaces these interfaces provide structure and functionality required by the elements used to create and manage forms, including the <form> and <input> elements.
... domstringlist domstringmap errorevent htmlallcollection mimetype mimetypearray promiserejectionevent interfaces belonging to other apis several interfaces are technically defined in the html specification while actually being part of other apis.
IDBDatabase.createObjectStore() - Web APIs
you can also pass in an array as a keypath.
... invalidaccesserror if autoincrement is set to true and keypath is either an empty string or an array containing an empty string.
IDBDatabase.transaction() - Web APIs
storenames the names of object stores that are in the scope of the new transaction, declared as an array of strings.
...therefore the following lines are equivalent: var transaction = db.transaction(['my-store-name']); var transaction = db.transaction('my-store-name'); if you need to access all object stores in the database, you can use the property idbdatabase.objectstorenames: var transaction = db.transaction(db.objectstorenames); passing an empty array will throw an exception.
InputEvent.getTargetRanges() - Web APIs
the gettargetranges() property of the inputevent interface returns an array of static ranges that will be affected by a change to the dom if the input event is not canceled.
... return value an array of staticrange objects.
IntersectionObserver.takeRecords() - Web APIs
the intersectionobserver method takerecords() returns an array of intersectionobserverentry objects, one for each targeted element which has experienced an intersection change since the last time the intersections were checked, either explicitly through a call to this method or implicitly by an automatic call to the observer's callback.
... return value an array of intersectionobserverentry objects, one for each target element whose intersection with the root has changed since the last time the intersections were checked.
KeyboardLayoutMap.entries - Web APIs
the entries read-only property of the keyboardlayoutmap interface returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
... syntax keyboardlayoutmap.entries() value an array of the given keyboardlayoutmap object's own enumerable property [key, value] pairs.
KeyboardLayoutMap.forEach() - Web APIs
syntax keyboardlayoutmap.foreach(function callback(currentvalue[, index[, array]]) { //your iterator }[, thisarg]); parameters callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed.
... array optional the keyboardlayoutmap that foreach() is being called on.
KeyframeEffect.getKeyframes() - Web APIs
the getkeyframes() method of a keyframeeffect returns an array of the computed keyframes that make up this animation along with their computed offsets.
... examples in the red queen race example, we can inspect alice and the redqueen's animation to see its individual keyframes like so: // return the array of keyframes redqueen_alice.effect.getkeyframes(); specifications specification status comment web animationsthe definition of 'keyframeeffect.getkeyframes()' in that specification.
LockManager.query() - Web APIs
WebAPILockManagerquery
held: an array of lock objects for held locks.
... pending: an array of lock objects for pending lock requests.
MIDIMessageEvent - Web APIs
properties midiconnectionevent.data a uint8array containing the data bytes of a single midi message.
... examples // printing all messages to console navigator.requestmidiaccess().then(midiaccess => { array.from(midiaccess.inputs).foreach(input => { input[1].onmidimessage = console.log; }) }); specifications specification status comment web midi apithe definition of 'midimessageevent' in that specification.
MediaDevices.ondevicechange - Web APIs
the list is passed into the fulfillment handler as an array of mediadeviceinfo objects, each describing one media input or output device.
...this uses destructuring assignment (a new feature of ecmascript 6) to assign the values of the first three items in the array returned by string.match() to the variables kind, type, and direction.
MediaKeyStatusMap - Web APIs
methods mediakeystatusmap.entries() read only returns a new iterator object containing an array of [key, value] for each element in the status map, in insertion order.
... mediakeystatusmap.[@@iterator]() read only returns a new iterator object containing an array of [key, value] for each element in the status map, in insertion order.
MediaMetadata.artwork - Web APIs
the artwork property of the mediametadata interface returns or sets an array of mediaimage objects representing images associated with playing media.
... syntax var artwork[] = mediametadata.artwork mediametadata.artwork = artwork[] value an array of mediaimage objects.
MediaStream.getAudioTracks() - Web APIs
return value an array of mediastreamtrack objects, one for each audio track contained in the stream.
...the array is empty if the stream contains no audio tracks.
MediaStream.getVideoTracks() - Web APIs
return value an array of mediastreamtrack objects, one for each video track contained in the media stream.
...the array is empty if the stream contains no video tracks.
MediaStream Image Capture API - Web APIs
this returns an array of mediastreamtrack objects.
... the code below assumes that the first item in the mediastreamtrack array is the one to use.
MessageEvent.MessageEvent() - Web APIs
ports: an array of messageport objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g.
...this defaults to an empty array ([]) if not specified.
MessageEvent.ports - Web APIs
the ports read-only property of the messageevent interface is an array of messageport objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g.
... syntax var myports = messageevent.ports; value an array of messageport objects.
Navigator.getGamepads() - Web APIs
the navigator.getgamepads() method returns an array of gamepad objects, one for each gamepad connected to the device.
... elements in the array may be null if a gamepad disconnects during a session, so that the remaining gamepads retain the same index.
Navigator.requestMediaKeySystemAccess() - Web APIs
supportedconfigurations a non-empty array of mediakeysystemconfiguration objects.
... typeerror either keysystem is an empty string or the supportedconfigurations array is empty.
Navigator.vibrate() - Web APIs
WebAPINavigatorvibrate
you may provide either a single value (to vibrate once for that many milliseconds) or an array of values to alternately vibrate, pause, then vibrate again.
... passing a value of 0, an empty array, or an array containing all zeros will cancel any currently ongoing vibration pattern.
NavigatorPlugins - Web APIs
properties navigatorplugins.mimetypes read only returns an mimetypearray listing the mime types supported by the browser.
... navigatorplugins.plugins read only returns a pluginarray listing the plugins installed in the browser.
Node - Web APIs
WebAPINode
if callback is omitted, the function returns an array instead, which contains rootnode and all nodes contained within.
...if omitted, eachnode returns an array of every node contained within rootnode (including the root itself).
OrientationSensor.quaternion - Web APIs
the quaternion read-only property of the orientationsensor interface returns a four element array whose elements contain the components of the unit quaternion representing the device's orientation.
... value a array whose values are the x, y, z, and w components of the quaternion representing the device orientation.
OrientationSensor - Web APIs
absoluteorientationsensor relativeorientationsensor properties orientationsensor.quaternion returns a four element array whose elements contain the components of the unit quaternion representing the device's orientation.
... model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requsting permissions for multiple device sensors.
ParentNode.children - Web APIs
you can access the individual child nodes in the collection by using either the item() method on the collection, or by using javascript array-style notation.
...// returns array instead of htmlcollection.
PaymentRequestEvent() - Web APIs
methoddata: an array of paymentmethoddata objects containing payment method identifers for the payment methods that the web site accepts and any associated payment method specific data.
... modifiers: an array of objects containing changes to payment details.
PaymentRequestEvent.methodData - Web APIs
the methoddata read-only property of the paymentrequestevent interface returns an array of paymentmethoddata objects containing payment method identifers for the payment methods that the web site accepts and any associated payment method specific data.
... syntax var methoddata[] = paymentrequestevent.methoddata value an array of paymentmethoddata objects.
PaymentRequestEvent.modifiers - Web APIs
the modifiers read-only property of the paymentrequestevent interface returns an array of objects containing changes to payment details.
... syntax var modifiers[] = paymentdetailsevent.modifiers value an array of modifier objects.
PaymentRequestEvent - Web APIs
methoddataread only returns an array of paymentmethoddata objects containing payment method identifers for the payment methods that the web site accepts and any associated payment method specific data.
... modifiersread only returns an array of objects containing changes to payment details.
PerformanceObserver.observe() - Web APIs
the performance entry types are specified as an array of domstring objects, each naming one entry type; the type names are documented in performance entry type names in performanceentry.entrytype.
... syntax observer.observe(options); parameters options a performanceobserverinit dictionary with the following possible members: entrytypes: an array of domstring objects, each specifying one performance entry type to observe.
Multi-touch interaction - Web APIs
this application uses three arrays to cache event state, one cache per target element.
... // log events flag var logevents = false; // event caches, one per touch target var evcache1 = new array(); var evcache2 = new array(); var evcache3 = new array(); register event handlers event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup.
PushManager.supportedContentEncodings - Web APIs
the supportedcontentencodings read-only property of the pushmanager interface returns an array of supported content codings that can be used to encrypt the payload of a push message.
... syntax var encodings[] = pushmanager.supportedcontentencodings value an array of strings.
PushSubscription.getKey() - Web APIs
the getkey() method of the pushsubscription interface returns an arraybuffer representing a client public key, which can then be sent to a server and used in encrypting push message data.
... returns an arraybuffer.
RTCConfiguration.certificates - Web APIs
the rtcconfiguration dictionary's optional certificates property is an array of rtccertificate objects providing the security certificates available for use when authenticating duing the connection process.
...]; let certificates = rtcconfiguration.certificates; value an array of rtccertificate objects, each specifying one security certificate available for use when connecting to a remote peer.
RTCConfiguration - Web APIs
certificates optional an array of objects of type rtccertificate which are used by the connection for authentication.
... iceservers optional an array of rtciceserver objects, each describing one server which may be used by the ice agent; these are typically stun and/or turn servers.
RTCIceServer - Web APIs
objects of this type are provided in the configuration of an rtcpeerconnection, in the iceservers array.
... urls this required property is either a single domstring or an array of domstrings, each specifying a url which can be used to connect to the server.
RTCIceTransport.getLocalCandidates() - Web APIs
the rtcicetransport method getlocalcandidates() returns an array of rtcicecandidate objects, one for each of the candidates that have been gathered by the local device during the current ice agent session.
... return value a javascript array containing one rtcicecandidate object for each candidate that has been identified so far during the ice candidate gathering session.
RTCIceTransport.getRemoteCandidates() - Web APIs
the rtcicetransport method getremotecandidates() returns an array which contains one rtcicecandidate for each of the candidates that have been received from the remote peer so far during the current ice gathering session.
... return value an array containing one rtcicecandidate object for each candidate that has been received so far from the remote peer during the current ice candidate gathering session.
RTCIceTransport - Web APIs
getlocalcandidates() returns an array of rtcicecandidate objects, each describing one of the ice candidates that have been gathered so far for the local device.
... getremotecandidates() returns an array of rtcicecandidate objects, one for each of the remote device's ice candidates that have been received by the local end of the rtcpeerconnection and delivered to ice by calling addicecandidate().
RTCPeerConnection() - Web APIs
certificates optional an array of objects of type rtccertificate which are used by the connection for authentication.
... iceservers optional an array of rtciceserver objects, each describing one server which may be used by the ice agent; these are typically stun and/or turn servers.
RTCPeerConnection.getConfiguration() - Web APIs
let configuration = mypeerconnection.getconfiguration(); if ((configuration.certificates != undefined) && (!configuration.certificates.length)) { rtcpeerconnection.generatecertificate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]) }).then(function(cert) { configuration.certificates = [cert]; mypeerconnection.setconfiguration(configuration); }); } this example fetches the current configuration of the rtcpeerconnection, then looks to see if it has any certificates set by examining whether or not (a) the configuration has a value for certificates, and (b) whether its length is zero.
... if it's determined that there are no certificates in place, rtcpeerconnection.generatecertificate() is called to create a new certificate; we provide a fulfillment handler which adds a new array containing the one newly-created certificate to the current configuration and passes it to setconfiguration() to add the certificate to the connection.
RTCRtpParameters - Web APIs
to obtain the parameters of a sender or receiver, call its getparameters() method: getparameters() getparameters() properties codecs an array of rtcrtpcodecparameters objects describing the set of codecs from which the sender or receiver will choose.
... headerextensions an array of zero or more rtp header extensions, each identifying an extension supported by the sender or receiver.
RTCRtpReceiver.getContributingSources() - Web APIs
the getcontributingsources() method of the rtcrtpreceiver interface returns an array of rtcrtpcontributingsource instances, each corresponding to one csrc (contributing source) identifier received by the current rtcrtpreceiver in the last ten seconds.
... return value an array of rtcrtpcontributingsource instances.
RTCRtpReceiver.getSynchronizationSources() - Web APIs
the getsynchronizationsources() method of the rtcrtpreceiver interface returns an array of rtcrtpcontributingsource instances, each corresponding to one ssrc (synchronization source) identifier received by the current rtcrtpreceiver in the last ten seconds.
... return value an array of rtcrtpsynchronizationsource instances.
RTCRtpReceiver - Web APIs
methods rtcrtpreceiver.getcontributingsources() returns an array of rtcrtpcontributingsource instances for each unique csrc (contributing source) identifier received by the current rtcrtpreceiver in the last ten seconds.
... rtcrtpreceiver.getsynchronizationsources() returns an array including one rtcrtpsynchronizationsource instance for each unique ssrc (synchronization source) identifier received by the current rtcrtpreceiver in the last ten seconds.
RTCRtpSender.setStreams() - Web APIs
the rtcrtpsender method setstreams() associates the sender's track with the specified mediastream or array of mediastream objects.
... syntax rtcrtpsender.setstreams(mediastream); rtcrtpsender.setstreams([mediastream...]); parameters mediastream or [mediastream...] optional an mediastream object—or an array of multiple mediastream objects—identifying the streams to which the rtcrtpsender's track belongs.
RTCTrackEvent.streams - Web APIs
the webrtc api interface rtctrackevent's read-only streams property specifies an array of mediastream objects, one for each of the streams that comprise the track being added to the rtcpeerconnection.
... syntax var streams = trackevent.streams; value an array of mediastream objects, one for each stream that make up the new track.
ReadableStreamDefaultReader - Web APIs
it demonstrates the usage of a readablestream in combination with a uint8array.
... fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" return reader.read().then(({ done, value }) => { // is there no more data to read?
Request - Web APIs
WebAPIRequest
request implements body, so it also has the following methods available to it: body.arraybuffer() returns a promise that resolves with an arraybuffer representation of the request body.
... note: the body functions can be run only once; subsequent calls will resolve with empty strings/arraybuffers.
Response - Web APIs
WebAPIResponse
body interface methods response implements body, so it also has the following methods available to it: body.arraybuffer() takes a response stream and reads it to completion.
... it returns a promise that resolves with an arraybuffer.
Screen.lockOrientation() - Web APIs
this is either a string or an array of strings.
... examples usage with a domstring argument screen.lockorientationuniversal = screen.lockorientation || screen.mozlockorientation || screen.mslockorientation; if (screen.lockorientationuniversal("landscape-primary")) { // orientation was locked } else { // orientation lock failed } usage with an array argument screen.lockorientationuniversal = screen.lockorientation || screen.mozlockorientation || screen.mslockorientation; if (screen.lockorientationuniversal(["landscape-primary", "landscape-secondary"])) { // orientation was locked } else { // orientation lock failed } specifications specification status comment screen orientation apithe definition of 'locko...
ServiceWorkerContainer - Web APIs
serviceworkercontainer.getregistrations() returns all serviceworkerregistration objects associated with a serviceworkercontainer in an array.
... the method returns a promise that resolves to an array of serviceworkerregistration.
ServiceWorkerMessageEvent.ports - Web APIs
the ports read-only property of the serviceworkermessageevent interface returns an array of messageport objects connected with the message channel the message is being sent through.
... syntax var myports = serviceworkermessageeventinstance.ports; value an array of messageport objects.
SourceBuffer.appendBuffer() - Web APIs
the appendbuffer() method of the sourcebuffer interface appends media segment data from an arraybuffer or arraybufferview object to the sourcebuffer.
... syntax sourcebuffer.appendbuffer(source); parameters source a buffersource (that is, either an arraybufferview or arraybuffer) which contains the media segment data you want to add to the sourcebuffer.
SourceBuffer.appendBufferAsync() - Web APIs
the appendbufferasync() method of the sourcebuffer interface begins the process of asynchronously appending media segment data from an arraybuffer or arraybufferview object to the sourcebuffer.
... syntax appendpromise = sourcebuffer.appendbufferasync(source); parameters source a buffersource (that is, either an arraybufferview or arraybuffer) which contains the media segment data you want to add to the sourcebuffer.
SourceBuffer - Web APIs
sourcebuffer.appendbuffer() appends media segment data from an arraybuffer or arraybufferview object to the sourcebuffer.
...r(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); } function fetchab (url, cb) { console.log(url); var xhr = new xmlhttprequest; xhr.open('get', url); xhr.responsetype = 'arraybuffer'; xhr.onload = function () { cb(xhr.response); }; xhr.send(); } specifications specification status comment media source extensionsthe definition of 'sourcebuffer' in that specification.
SourceBufferList - Web APIs
the individual source buffers can be accessed using array operator (i.e.
... sourcebufferlist: indexed property getter this getter allows the sourcebuffer objects in the list to be accessed with an array operator (i.e.
SpeechRecognition.onresult - Web APIs
// it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
SpeechRecognitionAlternative.confidence - Web APIs
// it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
SpeechRecognitionAlternative.transcript - Web APIs
// it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
SpeechRecognitionAlternative - Web APIs
// it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
SpeechRecognitionEvent.resultIndex - Web APIs
the resultindex read-only property of the speechrecognitionevent interface returns the lowest index value result in the speechrecognitionresultlist "array" that has actually changed.
... the speechrecognitionresultlist object is not an array, but it has a getter that allows it to be accessed by array syntax.
SpeechRecognitionResult.isFinal - Web APIs
// it has a getter so it can be accessed like an array // the first [0] returns the speechrecognitionresult at position 0.
... // these also have getters so they can be accessed like arrays.
Streams API concepts - Web APIs
a chunk can be a single byte, or it can be something larger such as a typed array of a certain size.
... in javascript, this is achieved via the readablestream.tee() method — it outputs an array containing two identical copies of the original readable stream, which can then be read independently by two separate readers.
Using readable streams - Web APIs
note: in order to consume a stream using fetchevent.respondwith(), the enqueued stream contents must be of type uint8array; for example, encoded using textencoder.
...this is achieved via the readablestream.tee() method — it outputs an array containing two identical copies of the original readable stream, which can then be read independently by two separate readers.
Using writable streams - Web APIs
the constructor call in our example looks like this: const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); l...
... with the chunks encoded, we then call array/foreach on the resulting array.
StylePropertyMapReadOnly.entries() - Web APIs
the stylepropertymapreadonly.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
... return value an array of the given stylepropertymapreadonly object's own enumerable property [key, value] pairs.
StylePropertyMapReadOnly.forEach() - Web APIs
syntax stylepropertymapreadonly.foreach(function callback(currentvalue[, index[, array]]) { //your code }[, thisarg]); parameters callback the function to execute for each element, taking three arguments: currentvalue the value of the current element being processed.
... arrayoptional the stylepropertymapreadonly thatforeach() is being called on.
StylePropertyMapReadOnly.get() - Web APIs
we create an array of properties of interest and use the stylepropertymapreadonly's get() method to get only those values.
... // get the element const myelement = document.queryselector('a'); // get the <dl> we'll be populating const styleslist = document.queryselector('#regurgitation'); // retrieve all computed styles with computedstylemap() const stylemap = myelement.computedstylemap(); // array of properties we're interested in const ofinterest = ['font-weight', 'border-left-color', 'color', '--colour']; // iterate thru our properties of interest for ( let i = 0; i < ofinterest.length; i++ ) { // properties const cssproperty = document.createelement('dt'); cssproperty.appendchild(document.createtextnode(ofinterest[i])); styleslist.appendchild(cssproperty); // values const cssvalue = document.createelement('dd'); cssvalue.appendchild(document.createtextnode( stylemap.get(ofinterest[i]))); sty...
StylePropertyMapReadOnly.getAll() - Web APIs
the getall() method of the stylepropertymapreadonly interface returns an array of cssstylevalue objects containing the values for the provided property.
... return value an array of cssstylevalue objects.
StylePropertyMapReadOnly.keys() - Web APIs
the stylepropertymapreadonly.keys() method returns a new array iterator containing the keys for each item in stylepropertymapreadonly syntax stylepropertymapreadonly.keys() parameters none.
... return value a new array.
StylePropertyMapReadOnly.values() - Web APIs
the stylepropertymapreadonly.values() method returns a new array iterator containing the values for each index in the stylepropertymapreadonly object.
... return value a new array.
SubtleCrypto.deriveKey() - Web APIs
keyusages is an array indicating what can be done with the derived key.
...possible values of the array are: encrypt: the key may be used to encrypt messages.
SubtleCrypto.sign() - Web APIs
WebAPISubtleCryptosign
data is an arraybuffer or arraybufferview object containing the data to be signed.
... return value signature is a promise that fulfills with an arraybuffer containing the signature.
SubtleCrypto.verify() - Web APIs
signature is a arraybuffer containing the signature to verify.
... data is a arraybuffer containing the data whose signature is to be verified.
TextDecoder.prototype.decode() - Web APIs
syntax b1 = decoder.decode(buffer, options); b2 = decoder.decode(buffer); b3 = decoder.decode(); parameters buffer optional is either an arraybuffer or an arraybufferview containing the text to decode.
... html <p>encoded value: <span id="encoded-value"></span></p> <p>decoded value: <span id="decoded-value"></span></p> javascript const encoder = new textencoder(); const array = encoder.encode('€'); // uint8array(3) [226, 130, 172] document.getelementbyid('encoded-value').textcontent = array; const decoder = new textdecoder(); const str = decoder.decode(array); // string "€" document.getelementbyid('decoded-value').textcontent = str; result specifications specification status comment encodingthe definition of 'textdecoder.decode()' in ...
TextEncoder.prototype.encode() - Web APIs
the textencoder.prototype.encode() method takes a usvstring as input, and returns a uint8array containing the text given in parameters encoded with the specific method for that textencoder object.
... return value a uint8array object.
Multi-touch interaction - Web APIs
// log events flag var logevents = false; // touch point cache var tpcache = new array(); register event handlers event handlers are registered for all four touch event types.
...ches[0].clientx); var diff2 = math.abs(tpcache[point2].clientx - ev.targettouches[1].clientx); // this threshold is device dependent as well as application specific var pinch_threshhold = ev.target.clientwidth / 10; if (diff1 >= pinch_threshhold && diff2 >= pinch_threshhold) ev.target.style.background = "green"; } else { // empty tpcache tpcache = new array(); } } } touch start handler the touchstart event handler caches touch points to support 2-touch gestures.
TrackDefault.TrackDefault() - Web APIs
kinds an array (sequence) of domstrings specifying default kinds for the sourcebuffer to use when an initialization segment does not contain kind information for a new track.
... typeerror there are values specified in the kinds array that do not apply to the specified type.
TransformStream - Web APIs
methods none examples anything-to-uint8array stream in the following example, a transform stream passes through all chunks it receives as uint8array values.
... async transform(chunk, controller) { chunk = await chunk switch (typeof chunk) { case 'object': // just say the stream is done i guess if (chunk === null) controller.terminate() else if (arraybuffer.isview(chunk)) controller.enqueue(new uint8array(chunk.buffer, chunk.byteoffset, chunk.bytelength)) else if (array.isarray(chunk) && chunk.every(value => typeof value === 'number')) controller.enqueue(new uint8array(chunk)) else if ('function' === typeof chunk.valueof && chunk.valueof() !== chunk) this.transform(chunk.valueof(), controller) // hack else if ('tojson' in chunk) this.transform(json.stringify(chunk), controller) break case 's...
URLSearchParams.getAll() - Web APIs
the getall() method of the urlsearchparams interface returns all the values associated with a given search parameter as an array.
... return value an array of usvstrings.
USB.getDevices() - Web APIs
WebAPIUSBgetDevices
the getdevices method of the usb interface returns a promise that resolves with an array of usbdevice objects for paired attached devices.
... return value a promise that resolves with an array of usbdevice objects.
USBConfiguration.interfaces - Web APIs
the interfaces read-only property of the usbconfiguration interface returns an array containing instances of the usbinterface describing each interface supported by this configuration.
... syntax var interfaces[] = usbconfiguration.interfaces value an array containing instances of usbinterface.
USBDevice.configurations - Web APIs
the configurations read only property of the usbdevice interface an array of device-specific interfaces for controlling a paired usb device.
... syntax var usbconfiguration[] = usbdevice.configurations value an array of usbconfiguration objects.
USBDevice.isochronousTransferOut() - Web APIs
data a typedarray containing the data to send to the device.
... packetlengths an array of lengths for the packets being transfered.
USBDevice.opened - Web APIs
WebAPIUSBDeviceopened
async setdevicecolor(usbdevice, r, g, b) { if (device.opened) { // this hypothetical usb device requires that the data passed to // it be in a uint8array.
... let payload = new uint8array([r, g, b]); await usbdevice.controltransferout({ requesttype: 'vendor', recipient: 'device', request: 1, value: 0, index: 0, }, payload); } } specifications specification status comment webusbthe definition of 'opened' in that specification.
USBIsochronousInTransferResult - Web APIs
see the individual dataview objects in the packets array for the portion of this buffer containing data from each packet.
... usbisochronousintransferresult.packetsread only returns an array of usbisochronousintransferpacket objects containing the result of each request to receive a packet from the device.
VideoTrack.label - Web APIs
WebAPIVideoTracklabel
example this example returns an array of track kinds and labels for potential use in a user interface to select video tracks for a specified media element.
... function gettracklist(el) { var tracklist = []; const wantedkinds = [ "main", "alternative", "commentary" ]; el.videotracks.foreach(function(track) { if (wantedkinds.includes(track.kind)) { tracklist.push({ id: track.id, kind: track.kind, label: track.label }); } }); return tracklist; } the resulting tracklist contains an array of video tracks whose kind is one of those in the array wantedkinds, with each entry providing the track's id, kind, and label.
WEBGL_compressed_texture_astc.getSupportedProfiles() - Web APIs
the webgl_compressed_texture_astc.getsupportedprofiles() method returns an array of strings containing the names of the astc profiles supported by the implementation.
... syntax sequence<domstring> ext.getsupportedprofiles(); return value an array of domstring elements indicating which astc profiles are supported by the implementation.
WEBGL_compressed_texture_astc - Web APIs
ext.getsupportedprofiles() returns an array of strings containing the names of the astc profiles supported by the implementation.
... constants blocks bits per pixel arraybuffer bytelength bytes if height and width are 512 ext.compressed_rgba_astc_4x4_khr ext.compressed_srgb8_alpha8_astc_4x4_khr 4x4 8.00 floor((width + 3) / 4) * floor((height + 3) / 4) * 16 262144 ext.compressed_rgba_astc_5x4_khr ext.compressed_srgb8_alpha8_astc_5x4_khr 5x4 6.40 floor((width + 4) / 5) * floor((height + 3) / 4) * 16 210944 ext.compressed_rgba_astc_5x5_khr ext.compressed_srgb8_alpha8_astc_5x5_khr 5x5 5.12 floor((width + 4) / 5) * floor((height + 4) / 5) * 16 169744 ext.compresse...
WaveShaperNode - Web APIs
waveshapernode.curve is a float32array of numbers describing the distortion to apply.
...amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } return curve; }; ...
WebGL2RenderingContext.clearBuffer[fiuv]() - Web APIs
values an array of glint, gluint or glfloat values or an int32array, uint32array or float32array specifying the values to clear to.
... examples gl.clearbufferiv(gl.color, 0, new int32array([r, g, b, a])); gl.clearbufferuiv(gl.color, 0, new uint32array([r, g, b, a])); gl.clearbufferfv(gl.color, 0, new float32array([r, g, b, a])); gl.clearbufferfv(gl.color, 0, [0.0, 0.0, 0.0, 0.0]); gl.clearbufferfi(gl.depth_stencil, 0, 1.0, 0); specifications specification status comment webgl 2.0the definition of 'clearbuffer[fiuv]()' in that specification.
WebGL2RenderingContext.getInternalformatParameter() - Web APIs
possible values: gl.samples: returns a int32array containing sample counts supported for internalformat in descending order.
...it is an int32array if pname is gl.samples.
WebGL2RenderingContext.getUniformIndices() - Web APIs
uniformnames an array of domstring specifying the names of the uniforms to query.
... return value an array of gluint containing the uniform indices.
WebGL2RenderingContext.texStorage3D() - Web APIs
the webgl2renderingcontext.texstorage3d() method of the webgl api specifies all levels of a three-dimensional texture or two-dimensional array texture.
... gl.texture_2d_array: a two-dimensional array texture.
WebGL2RenderingContext.vertexAttribDivisor() - Web APIs
the webgl2renderingcontext.vertexattribdivisor() method of the webgl 2 api modifies the rate at which generic vertex attributes advance when rendering multiple instances of primitives with gl.drawarraysinstanced() and gl.drawelementsinstanced().
... note: when using webgl 1, the angle_instanced_arrays extension can provide this method, too.
WebGLRenderingContext.blendColor() - Web APIs
examples to set the blend color, use: gl.blendcolor(0, 0.5, 1, 1); to get the blend color, query the blend_color constant which returns a float32array.
... gl.getparameter(gl.blend_color); // float32array[0, 0.5, 1, 1] specifications specification status comment webgl 1.0the definition of 'blendcolor' in that specification.
WebGLRenderingContext.clearColor() - Web APIs
examples gl.clearcolor(1, 0.5, 0.5, 3); to get the current clear color, query the color_clear_value constant which returns a float32array.
... gl.getparameter(gl.color_clear_value); // float32array[1, 0.5, 0.5, 1] specifications specification status comment webgl 1.0the definition of 'clearcolor' in that specification.
WebGLRenderingContext.generateMipmap() - Web APIs
gl.texture_2d_array: a two-dimensional array texture.
... adds: gl.texture_3d and gl.texture_2d_array ...
WebGLRenderingContext.getExtension() - Web APIs
the current extensions are: angle_instanced_arrays ext_blend_minmax ext_color_buffer_float ext_color_buffer_half_float ext_disjoint_timer_query ext_float_blend ext_frag_depth ext_srgb ext_shader_texture_lod ext_texture_compression_bptc ext_texture_compression_rgtc ext_texture_filter_anisotropic khr_parallel_shader_compile oes_element_index_uint oes_fbo_render_mipmap oes_standard_derivatives oes_texture_float oes_texture_float_...
...linear oes_texture_half_float oes_texture_half_float_linear oes_vertex_array_object ovr_multiview2 webgl_color_buffer_float webgl_compressed_texture_astc webgl_compressed_texture_atc webgl_compressed_texture_etc webgl_compressed_texture_etc1 webgl_compressed_texture_pvrtc webgl_compressed_texture_s3tc webgl_compressed_texture_s3tc_srgb webgl_debug_renderer_info webgl_debug_shaders webgl_depth_texture webgl_draw_buffers webgl_lose_context specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext.getextension' in that specification.
WebGLRenderingContext.getTexParameter() - Web APIs
gl.texture_2d_array: a two-dimensional array texture.
... gl.texture_max_level glint maximum texture mipmap array level any int values.
WebGLRenderingContext.getUniform() - Web APIs
return value the returned type depends on the uniform type: uniform type returned type webgl 1 only boolean glboolean int glint float glfloat vec2 float32array (with 2 elements) ivec2 int32array (with 2 elements) bvec2 array of glboolean (with 2 elements) vec3 float32array (with 3 elements) ivec3 int32array (with 3 elements) bvec3 array of glboolean (with 3 elements) vec4 float32array (with 4 elements) ivec4 int32array (with 4 elements) bvec4 array of glboole...
...an (with 4 elements) mat2 float32array (with 4 elements) mat3 float32array (with 9 elements) mat4 float32array (with 16 elements) sampler2d glint samplercube glint additionally available in webgl 2 uint gluint uvec2 uint32array (with 2 elements) uvec3 uint32array (with 3 elements) uvec4 uint32array (with 4 elements) mat2x3 float32array (with 6 elements) mat2x4 float32array (with 8 elements) mat3x2 float32array (with 6 elements) mat3x4 float32array (with 12 elements) mat4x2 float32array (with 8 elements) mat4x3 float32array (with 12 elements) any sampler type glint examples var loc = gl.get...
WebGLRenderingContext.getVertexAttribOffset() - Web APIs
pname a glenum which must be gl.vertex_attrib_array_pointer.
... examples gl.getvertexattriboffset(i, gl.vertex_attrib_array_pointer); specifications specification status comment webgl 1.0the definition of 'getvertexattriboffset' in that specification.
WebGLRenderingContext.scissor() - Web APIs
clear) // turn off scissor test again gl.disable(gl.scissor_test); to get the current scissor box dimensions, query the scissor_box constant which returns an int32array.
... gl.scissor(0, 0, 200, 200); gl.getparameter(gl.scissor_box); // int32array[0, 0, 200, 200] specifications specification status comment webgl 1.0the definition of 'scissor' in that specification.
WebGLRenderingContext.texParameter[fi]() - Web APIs
gl.texture_2d_array: a two-dimensional array texture.
... gl.texture_max_level maximum texture mipmap array level any int values.
WebGLRenderingContext.uniform[1234][fi][v]() - Web APIs
a sequence of floating point numbers (for example a float32array or an array of numbers) for floating point vector methods (methods with "fv").
... an int32array for integer vector methods (methods with "iv").
Hello vertex attributes - Web APIs
" + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); document.queryselector("canvas").addeventlistener("click", function (evt) { var clickxrelativtocanvas = evt.pagex - evt.target.offsetleft; var clickxinwebglcoords = 2.0 * (clickxrelativtocanvas- gl.drawingbufferwidth/2) / gl.drawingbufferwidth; gl.bufferdata(gl.array_buffer, new float32array([clickxinwebglcoords]), ...
...gl.static_draw); gl.drawarrays(gl.points, 0, 1); }, false); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array([0.0]), gl.static_draw); gl.vertexattribpointer(0, 1, gl.float, false, 0, 0); } window.addeventlistener("beforeunload", cleanup, true); function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer); if (program) gl.deleteprogram(program); } function getrenderingcontext() { var canvas = document.queryselector("canvas"); canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl)...
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
the latter is an array of mediastream objects, each representing a stream containing this track (a track may in rare cases belong to multiple streams at once).
...otherwise, we set srcobject to the stream at index 0 in the streams array.
Writing a WebSocket server in Java - Web APIs
outputstream methods: write(byte[] b, int off, int len) writes len bytes from the specified byte array starting at offset off to this output stream.
... inputstream methods: read(byte[] b, int off, int len) reads up to len bytes of data from the input stream into an array of bytes.
Web Animations API - Web APIs
document.getanimations() returns an array of animation objects currently in effect on elements in the document.
... element.getanimations() returns an array of animation objects currently affecting an element or which are scheduled to do so in future.
Advanced techniques: Creating and sequencing audio - Web APIs
loading the sample we want to make sure our file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(audiocontext, filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audiocontext.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can only run subsequent code when it has finished executing.
... let's create another async function to set up the sample — we can combine the two async functions in a nice promise pattern to perform further actions when this file is loaded and buffered: async function setupsample() { const filepath = 'dtmf.mp3'; const sample = await getfile(audioctx, filepath); return sample; } note: you can easily modify the above function to take an array of files and loop over them to load more than one sample.
Using the Web Speech API - Web APIs
it has a getter so it can be accessed like an array — so the first [0] returns the speechrecognitionresult at position 0.
...these also have getters so they can be accessed like arrays — the second [0] therefore returns the speechrecognitionalternative at position 0.
The structured clone algorithm - Web APIs
blob file filelist arraybuffer arraybufferview including other typed arrays.
... imagebitmap imagedata array object only plain objects (e.g.
window.postMessage() - Web APIs
secure shared memory messaging if postmessage() throws when used with sharedarraybuffer objects, you might need to make sure you cross-site isolated your site properly.
...r origin from attackers) cross-origin-embedder-policy with require-corp as value (protects victims from your origin) cross-origin-opener-policy: same-origin cross-origin-embedder-policy: require-corp to check if cross origin isolation has been successful, you can test against the crossoriginisolated property available to window and worker contexts: if (crossoriginisolated) { // post sharedarraybuffer } else { // do something else } see also planned changes to shared memory which is starting to roll out to browsers (firefox 79, for example).
Window - Web APIs
WebAPIWindow
window.frames read only returns an array of the subframes in the current window.
...this is an nsiarray.
WindowOrWorkerGlobalScope.btoa() - Web APIs
for example: // convert a unicode string to a string in which // each 16-bit unit occupies only one byte function tobinary(string) { const codeunits = new uint16array(string.length); for (let i = 0; i < codeunits.length; i++) { codeunits[i] = string.charcodeat(i); } return string.fromcharcode(...new uint8array(codeunits.buffer)); } // a string that contains characters occupying > 1 byte const mystring = "☸☹☺☻☼☾☿"; const converted = tobinary(mystring); const encoded = btoa(converted); console.log(encoded); // ocy5jjomoy...
...y8jj4mpyy= if you do this, of course you'll have to reverse the conversion on the decoded string: function frombinary(binary) { const bytes = new uint8array(binary.length); for (let i = 0; i < bytes.length; i++) { bytes[i] = binary.charcodeat(i); } return string.fromcharcode(...new uint16array(bytes.buffer)); } const decoded = atob(encoded); const original = frombinary(decoded); console.log(original); // ☸☹☺☻☼☾☿ polyfill you can use a polifill from https://github.com/maxart2501/base64-js/blob/master/base64.js for browsers that don't support it.
WindowOrWorkerGlobalScope.crossOriginIsolated - Web APIs
the crossoriginisolated read-only property of the windoworworkerglobalscope interface returns a boolean value that indicates whether a sharedarraybuffer can be sent via a window.postmessage() call.
... syntax var mycrossoriginisolated = self.crossoriginisolated; // or just crossoriginisolated value a boolean value examples if(crossoriginisolated) { // post sharedarraybuffer } else { // do something else } specifications specification status comment html living standardthe definition of 'crossoriginisolated' in that specification.
XMLHttpRequest.getAllResponseHeaders() - Web APIs
the code shows how to obtain the raw header string, as well as how to convert it into an array of individual headers and then how to take that array and create a mapping of header names to their values.
... var request = new xmlhttprequest(); request.open("get", "foo.txt", true); request.send(); request.onreadystatechange = function() { if(this.readystate == this.headers_received) { // get the raw header string var headers = request.getallresponseheaders(); // convert the header string into an array // of individual headers var arr = headers.trim().split(/[\r\n]+/); // create a map of header names to values var headermap = {}; arr.foreach(function (line) { var parts = line.split(': '); var header = parts.shift(); var value = parts.join(': '); headermap[header] = value; }); } } once this is done, you can, for example: var contenttype = headermap["content-type"]; this obtains the value of the content-type header into the variab...
XMLHttpRequest.response - Web APIs
the xmlhttprequest response property returns the response's body content as an arraybuffer, blob, document, javascript object, or domstring, depending on the value of the request's responsetype property.
... arraybuffer the response is a javascript arraybuffer containing binary data.
XMLHttpRequestResponseType - Web APIs
arraybuffer the response is a javascript arraybuffer containing binary data.
... deprecated values moz-chunked-arraybuffer a firefox-only value which instructs xmlhttprequest to deliver arraybuffer objects containing chunks of the incoming data.
XRBoundedReferenceSpace - Web APIs
these bounds are defined using an array of points, each of which defines a vertex in a polygon inside which the user is allowed to move.
... properties in addition to the properties of xrreferencespace, xrboundedreferencespace includes the following: boundsgeometry read only an array of dompointreadonly objects, each of which defines a vertex in the polygon defining the boundaries within which the user will be required to remain.
XRInputSource.profiles - Web APIs
the read-only xrinputsource property profiles returns an array of strings, each describing a configuration profile for the input source.
... syntax let profilelist = xrinputsource.profiles; value an array of domstring objects, each describing one configuration profile for the input device represented by the xrinputsource object.
XRInputSourcesChangeEvent.removed - Web APIs
the read-only xrinputsourceschangeevent property removed is an array of zero or more xrinputsource objects representing the input sources which have been removed from the xrsession.
... syntax removedinputs = xrinputsourceschangeevent.removed; value an array of zero or more xrinputsource objects, each representing one input device removed from the xr system.
XRInputSourcesChangeEvent - Web APIs
properties added read only an array of zero or more xrinputsource objects, each representing an input device which has been newly connected or enabled for use.
... removed read only an array of zero or more xrinputsource objects representing the input devices newly connected or enabled for use.
XRInputSourcesChangeEventInit.removed - Web APIs
the xrinputsourceschangeeventinit property removed is an array of zero or more xrinputsource objects, each representing one input source which has been removed from the xrsession.
... new xrinputsourceschangeeventinit("inputsourceschange", inputsourceseventinit); myinputsourceschangeevent = new xrinputsourceschangeeventinit("inputsourceschange", { session: xrsession, added: addeddevicelist, removed: removeddevicelist }); value an array of zero or more xrinputsource objects, each representing one input device removed from the xr system.
XRInputSourcesChangeEventInit - Web APIs
properties added read only an array of zero or more xrinputsource objects, each representing one input device which is newly available to use.
... removed read only an array of zero or more xrinputsource objects representing the input devices which are no longer available.
XRPermissionDescriptor - Web APIs
optionalfeatures an array of strings, each specifying the name of a webxr feature which is requested but not required for the app to function.
... requiredfeatures an array of strings giving the names of the webxr features for which permission must be obtained in order to use your app or site.
XRPermissionStatus.granted - Web APIs
the webxr device api's xrpermissionstatus interface's granted property is an array of strings, each identifying one of the webxr features for which permission has been granted as of the time at which the permission api's navigator.permissions.query() method was called.
... syntax grantedfeatures = xrpermissionstatus.granted; value an array of domstring objects, each identifying a single webxr feature which the app or site has been granted permission to use.
XRSession.inputSources - Web APIs
the read-only inputsources property of the xrsession interface returns an xrinputsourcearray object which lists all controllers and input devices which are expressly associated with the xr device and are currently available.
... syntax inputsources = xrsession.inputsources; value an xrinputsourcearray object listing all of the currently-connected input controllers which are linked specifically to the xr device currently in use.
XRSessionInit - Web APIs
optionalfeatures optional an array of values identifying features which the returned xrsession may optionally support.
... requiredfeatures optional an array of values which the returned xrsession must support.
XRViewerPose - Web APIs
properties in addition to the properties inherited from xrpose, xrviewerpose includes the following: views read only an array of xrview objects, one for each viewpoint on the scene which is needed to represent the scene to the user.
... to render a scene using the xrviewerpose representing the user's head, one would iterate over the views in the views array, rendering them one after another.
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
if you're not using a hash table to keep track of unique id's, store the child id's and objects for the last 50 or so events in a circular array.
...in other words, the assistive technology can say "give me all 20 children of this object into this array".
Ajax - Developer guides
WebGuideAJAX
possible values are the empty string (default), arraybuffer, blob, document, json, and text.
... the response property will contain the entity body according to responsetype, as an arraybuffer, blob, document, json, or string.
<input type="file"> - HTML: Hypertext Markup Language
WebHTMLElementinputfile
the filelist behaves like an array, so you can check its length property to get the number of selected files.
...update your selection.`; listitem.appendchild(para); } list.appendchild(listitem); } } } the custom validfiletype() function takes a file object as a parameter, then uses array.prototype.includes() to check if any value in the filetypes matches the file's type property.
Cross-Origin-Embedder-Policy - HTTP
examples certain features depend on cross-origin isolation you can only access certain features like sharedarraybuffer objects or performance.now() with unthrottled timers, if your document has a coep header with the value require-corp value set.
... to check if cross origin isolation has been successful, you can test against the crossoriginisolated property available to window and worker contexts: if (crossoriginisolated) { // post sharedarraybuffer } else { // do something else } avoiding coep blockage with cors if you enable coep using require-corp and have a cross origin resource that needs to be loaded, it needs to support cors and you need to explicitly mark the resource as loadable from another origin to avoid blockage from coep.
Cross-Origin-Opener-Policy - HTTP
examples certain features depend on cross-origin isolation certain features like sharedarraybuffer objects or performance.now() with unthrottled timers are only available if your document has a coop header with the value same-origin value set.
... to check if cross-origin isolation has been successful, you can test against the crossoriginisolated property available to window and worker contexts: if (crossoriginisolated) { // post sharedarraybuffer } else { // do something else } specifications specification html living standardthe definition of 'cross-origin-opener-policy header' in that specification.
Control flow and error handling - JavaScript
the example calls a function that retrieves a month name from an array based on the value passed to the function.
... function getmonthname(mo) { mo = mo - 1; // adjust month number for array index (1 = jan, 12 = dec) let months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; if (months[mo]) { return months[mo]; } else { throw 'invalidmonthno'; // throw keyword is used here } } try { // statements to try monthname = getmonthname(mymonth); // function could throw exception } catch (e) { monthname = 'unknown'; logmyerrors(e); // pass exception object to error handler (i.e.
Details of the object model - JavaScript
it adds the reports property (whose value defaults to an empty array, intended to have an array of employee objects as its value).
...it adds the projects property (whose value defaults to an empty array, intended to have an array of strings as its value).
Regular expression syntax cheatsheet - JavaScript
in results, matches to capturing groups typically in an array whose members are in the same order as the left parentheses in the capturing group.
...the matched substring cannot be recalled from the resulting array's elements ([1], ..., [n]) or from the predefined regexp object's properties ($1, ..., $9).
Groups and ranges - JavaScript
in results, matches to capturing groups typically in an array whose members are in the same order as the left parentheses in the capturing group.
...the matched substring cannot be recalled from the resulting array's elements ([1], ..., [n]) or from the predefined regexp object's properties ($1, ..., $9).
Inheritance and the prototype chain - JavaScript
// o ---> object.prototype ---> null var b = ['yo', 'whadup', '?']; // arrays inherit from array.prototype // (which has methods indexof, foreach, etc.) // the prototype chain looks like: // b ---> array.prototype ---> object.prototype ---> null function f() { return 2; } // functions inherit from function.prototype // (which has methods call, bind, etc.) // f ---> function.prototype ---> object.prototype ---> null with a constructor a "constructor" in javascript i...
... the only good reason for extending a built-in prototype is to backport the features of newer javascript engines, like array.foreach.
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
syntax var num = 15; string.replace(num, /5/, '2'); standard syntax var num = 15; string(num).replace(/5/, '2'); shim the following is a shim to provide support to non-supporting browsers: /*globals define*/ // assumes all supplied string instance methods already present // (one may use shims for these if not available) (function() { 'use strict'; var i, // we could also build the array of methods with the following, but the // getownpropertynames() method is non-shimable: // object.getownpropertynames(string).filter(function(methodname) { // return typeof string[methodname] === 'function'; // }); methods = [ 'contains', 'substring', 'tolowercase', 'touppercase', 'charat', 'charcodeat', 'indexof', 'lastindexof', 'startswith', 'endswith', ...
..., 'trimright', 'tolocalelowercase', 'normalize', 'tolocaleuppercase', 'localecompare', 'match', 'search', 'slice', 'replace', 'split', 'substr', 'concat', 'localecompare' ], methodcount = methods.length, assignstringgeneric = function(methodname) { var method = string.prototype[methodname]; string[methodname] = function(arg1) { return method.apply(arg1, array.prototype.slice.call(arguments, 1)); }; }; for (i = 0; i < methodcount; i++) { assignstringgeneric(methods[i]); } }()); ...
SyntaxError: for-in loop head declarations may not have initializers - JavaScript
"use strict"; var obj = {a: 1, b: 2, c: 3 }; for (var i in obj) { console.log(obj[i]); } array iteration the for...in loop shouldn't be used for array iteration.
... did you intend to use a for loop instead of a for-in loop to iterate an array?
SyntaxError: missing ; before statement - JavaScript
for example: var foo = 'tom's bar'; // syntaxerror: missing ; before statement you can use double quotes, or escape the apostrophe: var foo = "tom's bar"; var foo = 'tom\'s bar'; declaring properties with var you cannot declare properties of an object or array with a var declaration.
... var obj = {}; var obj.foo = 'hi'; // syntaxerror missing ; before statement var array = []; var array[0] = 'there'; // syntaxerror missing ; before statement instead, omit the var keyword: var obj = {}; obj.foo = 'hi'; var array = []; array[0] = 'there'; bad keywords if you come from another programming language, it is also common to use keywords that don't mean the same or have no meaning at all in javascript: def print(info){ console.log(info); }; // syntaxerror missing ; before statement instead, use function instead of def: function print(info){ console.log(info); }; ...
TypeError: "x" is read-only - JavaScript
message typeerror: assignment to read-only properties is not allowed in strict mode (edge) typeerror: "x" is read-only (firefox) typeerror: 0 is read-only (firefox) typeerror: cannot assign to read only property 'x' of #<object> (chrome) typeerror: cannot assign to read only property '0' of [object array] (chrome) error type typeerror what went wrong?
... 'use strict'; var obj = object.freeze({name: 'elsa', score: 157}); obj.score = 0; // typeerror 'use strict'; object.defineproperty(this, 'lung_count', {value: 2, writable: false}); lung_count = 3; // typeerror 'use strict'; var frozenarray = object.freeze([0, 1, 2]); frozenarray[0]++; // typeerror there are also a few read-only properties built into javascript.
Arrow function expressions - JavaScript
shorter functions var elements = [ 'hydrogen', 'helium', 'lithium', 'beryllium' ]; // this statement returns the array: [8, 6, 7, 9] elements.map(function(element) { return element.length; }); // the regular function above can be written as the arrow function below elements.map((element) => { return element.length; }); // [8, 6, 7, 9] // when there is only one parameter, we can remove the surrounding parentheses elements.map(element => { return element.length; }); // [8, 6, 7, 9] // when the only stateme...
...a : b; // easy array filtering, mapping, ...
Functions - JavaScript
rest parameters the rest parameter syntax allows representing an indefinite number of arguments as an array.
... arguments: an array-like object containing the arguments passed to the currently executing function.
Boolean - JavaScript
all other values, including any object, an empty array ([]), or the string "false", create an object with an initial value of true.
...with an initial value of false var bnoparam = new boolean(); var bzero = new boolean(0); var bnull = new boolean(null); var bemptystring = new boolean(''); var bfalse = new boolean(false); creating boolean objects with an initial value of true var btrue = new boolean(true); var btruestring = new boolean('true'); var bfalsestring = new boolean('false'); var bsulin = new boolean('su lin'); var barrayproto = new boolean([]); var bobjproto = new boolean({}); specifications specification ecmascript (ecma-262)the definition of 'boolean' in that specification.
DataView.prototype.buffer - JavaScript
the buffer accessor property represents the arraybuffer or sharedarraybuffer referenced by the dataview at construction time.
... examples using the buffer property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.buffer; // arraybuffer { bytelength: 8 } specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.buffer' in that specification.
DataView.prototype.byteOffset - JavaScript
the byteoffset accessor property represents the offset (in bytes) of this view from the start of its arraybuffer or sharedarraybuffer.
... examples using the byteoffset property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.byteoffset; // 0 (no offset specified) var dataview2 = new dataview(buffer, 3); dataview2.byteoffset; // 3 (as specified when constructing the dataview) specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.byteoffset' in that specification.
Intl.DateTimeFormat.prototype.format() - JavaScript
април 2013." using format with map use the format getter function for formatting all dates in an array.
... note that the function is bound to the intl.datetimeformat from which it was obtained, so it can be passed directly to array.prototype.map().
Intl.ListFormat - JavaScript
static methods intl.listformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
... intl.listformat.prototype.formattoparts() returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.
Intl.NumberFormat.prototype.format() - JavaScript
examples using format use the format getter function for formatting a single currency value, here for russia: var options = { style: 'currency', currency: 'rub' }; var numberformat = new intl.numberformat('ru-ru', options); console.log(numberformat.format(654321.987)); // → "654 321,99 руб." using format with map use the format getter function for formatting all numbers in an array.
... note that the function is bound to the numberformat from which it was obtained, so it can be passed directly to array.prototype.map.
Intl.NumberFormat - JavaScript
static methods intl.numberformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
... intl.numberformat.prototype.formattoparts() returns an array of objects representing the number string in parts that can be used for custom locale-aware formatting.
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
pluralcategories an array of plural categories used by the given locale, seleced from the list "zero", "one", "two", "few", "many" and "other".
... examples using the resolvedoptions method var de = new intl.pluralrules('de-de'); var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de-de" usedoptions.maximumfractiondigits; // 3 usedoptions.minimumfractiondigits; // 0 usedoptions.minimumintegerdigits; // 1 usedoptions.pluralcategories; // array [ "one", "other" ] usedoptions.type; // "cardinal" specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.pluralrules.prototype.resolvedoptions' in that specification.
Intl.RelativeTimeFormat - JavaScript
static methods intl.relativetimeformat.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
... intl.relativetimeformat.prototype.formattoparts() returns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting.
Intl.getCanonicalLocales() - JavaScript
the intl.getcanonicallocales() method returns an array containing the canonical locale names.
... return value an array containing the canonical locale names.
Map() constructor - JavaScript
syntax new map([iterable]) parameters iterable an array or other iterable object whose elements are key-value pairs.
... (for example, arrays with two elements, such as [[ 1, 'one' ],[ 2, 'two' ]].) each key-value pair is added to the new map.
Math.abs() - JavaScript
examples behavior of math.abs() passing an empty object, an array with more than one member, a non-numeric string or undefined/empty variable returns nan.
... passing null, an empty string or an empty array returns 0.
Math.fround() - JavaScript
however, sometimes you may be working with 32-bit floating-point numbers, for example if you are reading values from a float32array.
... polyfill this can be emulated with the following function, if float32array are supported: math.fround = math.fround || (function (array) { return function(x) { return array[0] = x, array[0]; }; })(new float32array(1)); supporting older browsers is slower, but also possible: if (!math.fround) math.fround = function(arg) { arg = number(arg); // return early for ±0 and nan.
Object.prototype.__proto__ - JavaScript
for objects created using array literals, this value is array.prototype.
...for objects created using new fun, where fun is one of the built-in constructor functions provided by javascript (array, boolean, date, number, object, string, and so on — including new constructors added as javascript evolves), this value is always fun.prototype.
Object.prototype.toLocaleString() - JavaScript
objects overriding tolocalestring array: array.prototype.tolocalestring() number: number.prototype.tolocalestring() date: date.prototype.tolocalestring() typedarray: typedarray.prototype.tolocalestring() bigint: bigint.prototype.tolocalestring() examples array tolocalestring() override on array objects, tolocalestring() can be used to print array values as a string, optionally with locale-specific identifiers (such as currency ...
...symbols) appended to them: for example: const testarray = [4, 7, 10]; let europrices = testarray.tolocalestring('fr', { style: 'currency', currency: 'eur'}); // "4,00 €,7,00 €,10,00 €" date tolocalestring() override on date objects, tolocalestring() is used to print out date displays more suitable for specific locales: for example: const testdate = new date(date.now()); // "date fri may 29 2020 18:04:24 gmt+0100 (british summer time)" let dedate = testdate.tolocalestring('de'); // "29.5.2020, 18:04:24" var frdate = testdate.tolocalestring('fr'); //"29/05/2020 à 18:04:24" number tolocalestring() override on number objects, tolocalestring() is used to print out number displays more suitable for specific locales, e.g.
Promise - JavaScript
if the returned promise resolves, it is resolved with an aggregating array of the values from the resolved promises ,in the same order as defined in the iterable of multiple promises.
... returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describe the outcome of each promise.
Comparing Reflect and Object methods - JavaScript
keys() object.keys() returns an array of strings that map to the target object's own (enumerable) property keys.
... n/a ownkeys() n/a reflect.ownkeys() returns an array of property names that map to the target object's own property keys.
Reflect.apply() - JavaScript
argumentslist an array-like object specifying the arguments with which target should be called.
... description in es5, you typically use the function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object).
RegExp.prototype[@@matchAll]() - JavaScript
let re = /[0-9]+/g; let str = '2016-01-02'; let result = re[symbol.matchall](str); console.log(array.from(result, x => x[0])); // ["2016", "01", "02"] using @@matchall in subclasses subclasses of regexp can override the [@@matchall]() method to modify the default behavior.
... for example, to return an array instead of an iterator: class myregexp extends regexp { [symbol.matchall](str) { const result = regexp.prototype[symbol.matchall].call(this, str); if (!result) { return null; } else { return array.from(result); } } } const re = new myregexp('([0-9]+)-([0-9]+)-([0-9]+)', 'g'); const str = '2016-01-02|2019-03-07'; const result = str.matchall(re); console.log(result[0]); // [ "2016-01-02", "2016", "01", "02" ] console.log(result[1]); // [ "2019-03-07", "2019", "03", "07" ] specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@matchall]' in that specification.
RegExp.prototype[@@split]() - JavaScript
the [@@split]() method splits a string object into an array of strings by separating the string into substrings.
... return value an array containing substrings as its elements.
String.prototype.localeCompare() - JavaScript
performance when comparing large numbers of strings, such as in sorting large arrays, it is better to create an intl.collator object and use the function provided by its compare property.
...lecompare() // the letter "a" is before "c" yielding a negative value 'a'.localecompare('c'); // -2 or -1 (or some other negative value) // alphabetically the word "check" comes after "against" yielding a positive value 'check'.localecompare('against'); // 2 or 1 (or some other positive value) // "a" and "a" are equivalent yielding a neutral value of zero 'a'.localecompare('a'); // 0 sort an array localecompare() enables case-insensitive sorting for an array.
String.prototype.toLocaleLowerCase() - JavaScript
if multiple locales are given in an array, the best available locale is used.
... a typeerror ("invalid element in locales argument") is thrown if an array element isn't of type string.
String.prototype.toLocaleUpperCase() - JavaScript
if multiple locales are given in an array, the best available locale is used.
... a typeerror ("invalid element in locales argument") is thrown if an array element isn't of type string.
String - JavaScript
the first is the charat() method: return 'cat'.charat(1) // returns "a" the other way (introduced in ecmascript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index: return 'cat'[1] // returns "a" when using bracket notation for character access, attempting to delete or assign a value to these properties will not succeed.
... string.prototype.split([sep [, limit] ]) returns an array of strings populated by splitting the calling string at occurences of the substring sep.
WebAssembly.Module() constructor - JavaScript
new webassembly.module(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile.
... examples synchronously compiling a webassembly module var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; function createwasmmodule(bytes) { return new webassembly.module(bytes); } fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = createwasmmodule(bytes); webassembly.instantiate(mod, importobject) .then(result => result.exports.exported_func() ); }) specifications specification webassembly javascript interfacethe definition of 'webassembly.module()' in that specification.
WebAssembly.Module.customSections() - JavaScript
return value a (possibly empty) array containing arraybuffer copies of the contents of all custom sections matching sectionname.
...since there is a "name" section in the example, an arraybuffer object is returned.
WebAssembly.Module.exports() - JavaScript
the webassembly.module.exports() function returns an array containing descriptions of all the declared exports of the given module.
... return value an array containing objects representing the exported functions of the given module.
WebAssembly.Module.imports() - JavaScript
the webassembly.imports() function returns an array containing descriptions of all the declared imports of the given module.
... return value an array containing objects representing the imported functions of the given module.
WebAssembly.Module - JavaScript
webassembly.module.exports() given a module, returns an array containing descriptions of all the declared exports.
... webassembly.module.imports() given a module, returns an array containing descriptions of all the declared imports.
Property accessors - JavaScript
syntax object.property object['property'] description one can think of an object as an associative array (a.k.a.
...the keys in this array are the names of the object's properties.
instanceof - JavaScript
for instance, [] instanceof window.frames[0].array will return false, because array.prototype !== window.frames[0].array and arrays inherit from the former.
...for instance, you can securely check if a given object is, in fact, an array using array.isarray(myobj) for example, checking if a nodes is a svgelement in a different context, you can use mynode instanceof mynode.ownerdocument.defaultview.svgelement.
yield* - JavaScript
console.log(iterator.next()); // {value: 2, done: false} console.log(iterator.next()); // {value: 3, done: false} console.log(iterator.next()); // {value: 4, done: false} console.log(iterator.next()); // {value: 5, done: false} console.log(iterator.next()); // {value: undefined, done: true} other iterable objects besides generator objects, yield* can also yield other kinds of iterables (e.g., arrays, strings, or arguments objects).
... function* g3() { yield* [1, 2]; yield* '34'; yield* array.from(arguments); } const iterator = g3(5, 6); console.log(iterator.next()); // {value: 1, done: false} console.log(iterator.next()); // {value: 2, done: false} console.log(iterator.next()); // {value: "3", done: false} console.log(iterator.next()); // {value: "4", done: false} console.log(iterator.next()); // {value: 5, done: false} console.log(iterator.next()); // {value: 6, done: false} console.log(iterator.next()); // {value: undefined, done: true} the value of yield* expression itself yield* is an expression, not a statement—so it evaluates to a value.
label - JavaScript
s labeled "loop2" if (i === 1 && j === 1) { continue loop1; } console.log('i = ' + i + ', j = ' + j); } } // output is: // "i = 0, j = 0" // "i = 0, j = 1" // "i = 0, j = 2" // "i = 1, j = 0" // "i = 2, j = 0" // "i = 2, j = 1" // "i = 2, j = 2" // notice how it skips both "i = 1, j = 1" and "i = 1, j = 2" using a labeled continue statement given an array of items and an array of tests, this example counts the number of items that passes all the tests.
... loop2: for (j = 0; j < 3; j++) { //the second for statement is labeled "loop2" if (i === 1 && j === 1) { break loop1; } console.log('i = ' + i + ', j = ' + j); } } // output is: // "i = 0, j = 0" // "i = 0, j = 1" // "i = 0, j = 2" // "i = 1, j = 0" // notice the difference with the previous continue example using a labeled break statement given an array of items and an array of tests, this example determines whether all items pass all tests.
with - JavaScript
however, ecmascript 2015 introduces a values property on array.prototype (so that it will be available on every array).
...however, in this particular example, array.prototype has been defined with values in its symbol.unscopables object.
Statements and declarations - JavaScript
for...of iterates over iterable objects (including arrays, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
... for await...of iterates over async iterable objects, array-like objects, iterators and generators, invoking a custom iteration hook with statements to be executed for the value of each distinct property.
d - SVG: Scalable Vector Graphics
WebSVGAttributed
<!-- first cubic command control points --> <line x1="10" y1="90" x2="30" y2="90" stroke="lightgrey" /> <circle cx="30" cy="90" r="1.5"/> <line x1="50" y1="10" x2="25" y2="10" stroke="lightgrey" /> <circle cx="25" cy="10" r="1.5"/> <!-- second smooth command control points (the first one is implicit) --> <line x1="50" y1="10" x2="75" y2="10" stroke="lightgrey" stroke-dasharray="2" /> <circle cx="75" cy="10" r="1.5" fill="lightgrey"/> <line x1="90" y1="90" x2="70" y2="90" stroke="lightgrey" /> <circle cx="70" cy="90" r="1.5" /> <!-- curve vertex points --> <circle cx="10" cy="90" r="1.5"/> <circle cx="50" cy="10" r="1.5"/> <circle cx="90" cy="90" r="1.5"/> </g> <use xlink:href="#controlpoints" x="100" /> </svg> quadratic bézier curv...
...-- highlight the curve vertex and control points --> <g> <polyline points="10,50 25,25 40,50" stroke="rgba(0,0,0,.2)" fill="none" /> <circle cx="25" cy="25" r="1.5" /> <!-- curve vertex points --> <circle cx="10" cy="50" r="1.5"/> <circle cx="40" cy="50" r="1.5"/> <g id="smoothquadraticdown"> <polyline points="40,50 55,75 70,50" stroke="rgba(0,0,0,.2)" stroke-dasharray="2" fill="none" /> <circle cx="55" cy="75" r="1.5" fill="lightgrey" /> <circle cx="70" cy="50" r="1.5" /> </g> <g id="smoothquadraticup"> <polyline points="70,50 85,25 100,50" stroke="rgba(0,0,0,.2)" stroke-dasharray="2" fill="none" /> <circle cx="85" cy="25" r="1.5" fill="lightgrey" /> <circle cx="100" cy="50" r="1.5" /> </g> <use xlink:href="#smoo...
dx - SVG: Scalable Vector Graphics
WebSVGAttributedx
e glyphs --> <line x1="0" x2="100%" y1="50%" y2="50%" /> <line x1="10%" x2="10%" y1="0" y2="100%" /> <line x1="60%" x2="60%" y1="0" y2="100%" /> <!-- some reference text --> <text x="10%" y="50%" fill="grey">svg</text> <!-- the same text with a shift along the x-axis --> <text dx="50%" x="10%" y="50%">svg</text> </svg> line { stroke: red; stroke-width: .5px; stroke-dasharray: 3px; } altglyph warning: as of svg2 <altglyph> is deprecated and shouldn't be used.
..." /> <line x1="30%" x2="30%" y1="0" y2="100%" /> <line x1="60%" x2="60%" y1="0" y2="100%" /> <!-- behaviors change based on the number of values in the attributes --> <text dx="20%" x="10%" y="25%">svg</text> <text dx="0 10%" x="10%" y="50%">svg</text> <text dx="0 10% 20%" x="10%" y="75%">svg</text> </svg> line { stroke: red; stroke-width: .5px; stroke-dasharray: 3px; } tref warning: as of svg2 <tref> is deprecated and shouldn't be used.
dy - SVG: Scalable Vector Graphics
WebSVGAttributedy
yphs --> <line x1="10%" x2="10%" y1="0" y2="100%" /> <line x1="0" x2="100%" y1="30%" y2="30%" /> <line x1="0" x2="100%" y1="80%" y2="80%" /> <!-- some reference text --> <text x="10%" y="30%" fill="grey">svg</text> <!-- the same text with a shift along the y-axis --> <text dy="50%" x="10%" y="30%">svg</text> </svg> line { stroke: red; stroke-width: .5px; stroke-dasharray: 3px; } altglyph warning: as of svg2 <altglyph> is deprecated and shouldn't be used.
...10" x2="10" y1="0" y2="100%" /> <line x1="50" x2="50" y1="0" y2="100%" /> <line x1="90" x2="90" y1="0" y2="100%" /> <!-- behaviors change based on the number of values in the attributes --> <text dy="20" x="10" y="30">svg</text> <text dy="0 10" x="50" y="30">svg</text> <text dy="0 10 20" x="90" y="30">svg</text> </svg> line { stroke: red; stroke-width: .5px; stroke-dasharray: 3px; } tref warning: as of svg2 <tref> is deprecated and shouldn't be used.
pathLength - SVG: Scalable Vector Graphics
stroke-dasharray, for example, will assume the start of the path being 0 and the end point the value defined in the pathlength attribute.
... seven elements are using this attribute: <circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, and <rect> html,body,svg { height:100% } <svg viewbox="0 0 100 60" xmlns="http://www.w3.org/2000/svg"> <style> path { fill: none; stroke: black; stroke-width: 2; stroke-dasharray: 10; } </style> <!-- no pathlength, the real length of the path is used.
stroke-linejoin - SVG: Scalable Vector Graphics
fill="none" stroke-linejoin="miter" /> <!-- effect of the "miter" value on a sharp angle where de default miter limit is exceeded --> <path d="m7,5 l0.75,-3 l0.75,3" stroke="black" fill="none" stroke-linejoin="miter" /> <!-- the following red dotted line show where the miter value falls back to the bevel value --> <path d="m0,0 h10" stroke="red" stroke-dasharray="0.05" stroke-width="0.025"/> <!-- the following pink lines highlight the position of the path for each stroke --> <g> <path d="m1,5 l2,-3 l2,3" stroke="pink" fill="none" stroke-width="0.025" /> <circle cx="1" cy="5" r="0.05" fill="pink" /> <circle cx="3" cy="2" r="0.05" fill="pink" /> <circle cx="5" cy="5" r="0.05" fill="pink" /> <path d="m7,5 l0.75,-3 l0.75,3" stroke=...
... stroke="black" fill="none" stroke-linejoin="miter-clip" /> <!-- effect of the "miter-clip" value on a sharp angle where de default miter limit is exceeded --> <path d="m7,5 l0.75,-3 l0.75,3" stroke="black" fill="none" stroke-linejoin="miter-clip" /> <!-- the following red dotted line show where the clip should happen --> <path d="m0,0 h10" stroke="red" stroke-dasharray="0.05" stroke-width="0.025"/> <!-- the following pink lines highlight the position of the path for each stroke --> <g> <path d="m1,5 l2,-3 l2,3" stroke="pink" fill="none" stroke-width="0.025" /> <circle cx="1" cy="5" r="0.05" fill="pink" /> <circle cx="3" cy="2" r="0.05" fill="pink" /> <circle cx="5" cy="5" r="0.05" fill="pink" /> <path d="m7,5 l0.75,-3 l0.75,3" stroke=...
x - SVG: Scalable Vector Graphics
WebSVGAttributex
<line x1="25%" y1="0" x2="25%" y2="100%" /> <line x1="50%" y1="0" x2="50%" y2="100%" /> <line x1="75%" y1="0" x2="75%" y2="100%" /> <!-- x with a single value --> <text y="40%" x="50%">svg</text> <!-- x with multiple values --> <text y="90%" x="25%, 50%, 75%">svg</text> </svg> text { font: 40px sans-serif; } line { fill: none; stroke: red; stroke-width: .5px; stroke-dasharray: 2px; } tref warning: as of svg2 <tref> is deprecated and shouldn't be used.
... y2="100%" /> <line x1="50%" y1="0" x2="50%" y2="100%" /> <line x1="75%" y1="0" x2="75%" y2="100%" /> <text> <!-- x with a single value --> <tspan y="40%" x="50%">svg</tspan> <!-- x with multiple values --> <tspan y="90%" x="25%, 50%, 75%">svg</tspan> </text> </svg> text { font: 40px sans-serif; } line { fill: none; stroke: red; stroke-width: .5px; stroke-dasharray: 2px; } use for <use>, x defines the x coordinate of the uper left corner of the referenced element.
y - SVG: Scalable Vector Graphics
WebSVGAttributey
ical line to materialized the x positioning --> <line x1="5%" y1="0" x2="5%" y2="100%" /> <line x1="55%" y1="0" x2="55%" y2="100%" /> <!-- y with a single value --> <text y="40%" x="5%">svg</text> <!-- y with multiple values --> <text y="40%,60%,80%" x="55%">svg</text> </svg> text { font: 40px sans-serif; } line { fill: none; stroke: red; stroke-width: .5px; stroke-dasharray: 2px; } tref warning: as of svg2 <tref> is deprecated and shouldn't be used.
...x positioning --> <line x1="5%" y1="0" x2="5%" y2="100%" /> <line x1="55%" y1="0" x2="55%" y2="100%" /> <text> <!-- y with a single value --> <tspan y="40%" x="5%">svg</tspan> <!-- y with multiple values --> <tspan y="40%,60%,80%" x="55%">svg</tspan> </text </svg> text { font: 40px sans-serif; } line { fill: none; stroke: red; stroke-width: .5px; stroke-dasharray: 2px; } use for <use>, y defines the y coordinate of the uper left corner of the referenced element.
SVG Attribute reference - SVG: Scalable Vector Graphics
WebSVGAttribute
icy refx refy rel rendering-intent repeatcount repeatdur requiredextensions requiredfeatures restart result rotate rx ry s scale seed shape-rendering slope spacing specularconstant specularexponent speed spreadmethod startoffset stddeviation stemh stemv stitchtiles stop-color stop-opacity strikethrough-position strikethrough-thickness string stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style surfacescale systemlanguage t tabindex tablevalues target targetx targety text-anchor text-decoration text-rendering textlength to transform transform-origin type u u1 u2 underline-position underline-thickness unicode unicode-bidi unicode-range units-per-em ...
... fill-rule, filter, flood-color, flood-opacity, font-family, font-size, font-size-adjust, font-stretch, font-style, font-variant, font-weight, glyph-orientation-horizontal, glyph-orientation-vertical, image-rendering, kerning, letter-spacing, lighting-color, marker-end, marker-mid, marker-start, mask, opacity, overflow, pointer-events, shape-rendering, stop-color, stop-opacity, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, text-decoration, text-rendering, transform, transform-origin, unicode-bidi, vector-effect, visibility, word-spacing, writing-mode filters attributes filter primitive attributes height, result, width, x, y transfer function attributes type, tablevalues, slope, intercept, amplitud...
SVG documentation index - SVG: Scalable Vector Graphics
WebSVGIndex
202 stroke svg, svg attribute the stroke attribute is a presentation attribute defining the color (or any svg paint servers like gradients or patterns) used to paint the outline of the shape; 203 stroke-dasharray svg, svg attribute the stroke-dasharray attribute is a presentation attribute defining the pattern of dashes and gaps used to paint the outline of the shape; 204 stroke-dashoffset svg, svg attribute the stroke-dashoffset attribute is a presentation attribute defining an offset on the rendering of the associated dash array.
...many browsers support svg images in: 292 svg documentation index svg found 383 pages: 293 svg element reference drawing, elements, responsive design, svg, svg reference, vector graphics, l10n:priority svg drawings and images are created using a wide array of elements which are dedicated to the construction, drawing, and layout of vector images and diagrams.
Example - SVG: Scalable Vector Graphics
velocity:</label> <input id='max_velocity' value='15'/> <br/> <label>attraction to cursor:</label> <input id='attract_cursor' value='6'/> <br/> <label>repulsion from peers:</label> <input id='repel_peer' value='5'/> <br/> </p> </form> <script type='text/javascript'> <![cdata[ // array of motes var motes; // get the display element.
... // return this as a 2-tuple (x,y) in an array function dimensions() { // our rendering element var display = display(); var width = parseint( display.getattributens(null,'width') ); var height = parseint( display.getattributens(null,'height') ); return [width,height]; } // this is called by mouse move events var mouse_x = 200, mouse_y = 150; function onmousemove(evt) { mouse_x = evt.clientx; mouse_y = evt.clienty; var widget = document.getelementbyid('cursor'); widget.setattributens(null,'cx',mouse_x); widget.setattributens(null,'cy',mouse_y); } document.onmousemove = onmousemove; // determine (x,y) of the cursor ...
Tutorials
after that, we discuss some key javascript features in detail, such as variables, strings, numbers and arrays.
... intermediate level introducing javascript objects in javascript, most things are objects, from core javascript features like strings and arrays to the browser apis built on top of javascript.
WebAssembly Concepts - WebAssembly
memory: a resizable arraybuffer that contains the linear array of bytes read and written by webassembly’s low-level memory access instructions.
... table: a resizable typed array of references (e.g.
WebAssembly
webassembly.memory() a webassembly.memory object is a resizable arraybuffer that holds the raw bytes of memory accessed by an instance.
... webassembly.table() a webassembly.table object is a resizable typed array of opaque values, like function references, that are accessed by an instance.
Modules - Archive of obsolete content
the resolved id is then further resolved using the paths array: const { loader, main } = require('toolkit/loader'); let loader = loader({ paths: ["./": "http://www.foo.com/"], resolve: function (id, requirer) { // your code here return id; } }); main(loader, "./main.js"); cuddlefish uses a custom resolve function to implement a form of access control: modules can only require modules for which they have been explicitly granted ...
Two Types of Scripts - Archive of obsolete content
api add-on code content script the global objects defined in the core javascript language, such as math, array, and json.
clipboard - Archive of obsolete content
this property is an array contains all types in which the data currently on the clipboard is available.
indexed-db - Archive of obsolete content
tems"], "readwrite"); var store = trans.objectstore("items"); var time = new date().gettime(); var request = store.put({ "name": name, "time": time }); request.onerror = database.onerror; }; function getitems(callback) { var cb = callback; var db = database.db; var trans = db.transaction(["items"], "readwrite"); var store = trans.objectstore("items"); var items = new array(); trans.oncomplete = function() { cb(items); } var keyrange = idbkeyrange.lowerbound(0); var cursorrequest = store.opencursor(keyrange); cursorrequest.onsuccess = function(e) { var result = e.target.result; if(!!result == false) return; items.push(result.value.name); result.continue(); }; cursorrequest.onerror = database.onerror; }; function listitem...
request - Archive of obsolete content
nested objects & arrays should encode safely.
ui - Archive of obsolete content
you initialize a toolbar with an array of buttons and frames: var ui = require("sdk/ui"); var { actionbutton } = require("sdk/ui/button/action"); var { toolbar } = require("sdk/ui/toolbar"); var { frame } = require("sdk/ui/frame"); var previous = ui.actionbutton({ id: "previous", label: "previous", icon: "./icons/previous.png" }); var next = ui.actionbutton({ id: "next", label: "next", icon: "./icons/next.png" }); var...
console/traceback - Archive of obsolete content
the stack is represented as an array in which the most recent stack frame is the last element; each element thus represents a stack frame and has the following keys: filename the name of the file that the stack frame takes place in.
content/loader - Archive of obsolete content
any kind of jsonable value (object, array, string, etc.) can be used here.
dev/panel - Archive of obsolete content
nstructor exports.mypanel = mypanel; // create a new tool, initialized // with the new constructor const mytool = new tool({ panels: { mypanel: mypanel } }); in the panel document script: // my-panel.js window.addeventlistener("message", function(event) { var content = document.getelementbyid("content"); content.textcontent = event.data; }); note that at the moment you have to pass an array of ports into postmessage, even if you don't need to use them: // main.js // require the sdk modules const { panel } = require("dev/panel"); const { tool } = require("dev/toolbox"); const { class } = require("sdk/core/heritage"); const mypanel = class({ extends: panel, label: "my panel", tooltip: "my new devtool's panel", icon: "./my-icon.png", url: "./my-panel.html", setup: functi...
frame/hidden-frame - Archive of obsolete content
parameters options : object required options: name type onready function,array functions to call when the frame is ready to load content.
platform/xpcom - Archive of obsolete content
it is passed an interface identifier and searches for the identifier in the interfaces property of: this object any of this object's ancestors any classes in the implements array property of the instance (for example, any classes added to this object via the implements option defined in heritage).
preferences/service - Archive of obsolete content
returns array : returns an array of strings representing the child preferences of the root of this branch.
system/xul-app - Archive of obsolete content
parameters names : array an array of host application names.
ui/sidebar - Archive of obsolete content
here's an add-on that adds each worker to an array in the attach handler, and makes sure that its references are cleaned up by listening to detach and removing workers as they are detached: var workerarray = []; function attachworker(worker) { workerarray.push(worker); } function detachworker(worker) { var index = workerarray.indexof(worker); if(index != -1) { workerarray.splice(index, 1); } } var sidebar = require("sdk/ui/sidebar...
Low-Level APIs - Archive of obsolete content
util/array helper functions for working with arrays.
Developing for Firefox Mobile - Archive of obsolete content
test/assert supported test/harness supported test/httpd supported test/runner supported test/utils supported ui/button/action not supported ui/button/toggle not supported ui/frame not supported ui/id supported ui/sidebar not supported ui/toolbar not supported util/array supported util/collection supported util/deprecate supported util/list supported util/match-pattern supported util/object supported util/uuid supported window/utils supported ...
Modifying Web Pages Based on URL - Archive of obsolete content
you can pass a single match-pattern string, or an array.
Bookmarks - Archive of obsolete content
var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var bookmarksarray = bmsvc.getbookmarkidsforuri(uri, {}); after executing this code, the array bookmarksarray contains the ids of all bookmarks that refer to the specified uri (in this case, "http://google.com").
Canvas code snippets - Archive of obsolete content
function savecanvas(canvas, path, type, options) { return task.spawn(function *() { var reader = new filereader; var blob = yield new promise(accept => canvas.toblob(accept, type, options)); reader.readasarraybuffer(blob); yield new promise(accept => { reader.onloadend = accept }); return yield os.file.writeatomic(path, new uint8array(reader.result), { tmppath: path + '.tmp' }); }); } loading a remote page onto a canvas element the following class first creates a hidden iframe element and attaches a listener to the frame's load event.
Modules - Archive of obsolete content
the use of eval() will probably not be of concern because it is only being used on the exported_symbols array which should not depend on user input.
Preferences - Archive of obsolete content
another caveat you should be aware of is that nsiprefbranch.getchildlist("",{}) returns an array of preference names that start with that branch's root, for example var branch = prefs.getbranch("accessibility."); var children = branch.getchildlist("", {}); will return these items (for the example tree above): "typeaheadfind.autostart", "typeaheadfind.enablesound", and "usebrailledisplay", not just direct children ("typeaheadfind" and "usebrailledisplay"), as you might have expected.
QuerySelector - Archive of obsolete content
// if you'd like to convert it to a array for convenience, use this instead: // return array.prototype.slice.call(el.queryselectorall(selector)); } alert($('#myid').id); (note that while using the firefox web console, the above functions are available automatically.) both xul and even xml can be easily made supportable (an alternative approach to the following would be to add chromewindow.prototype or window.prototype, accessing th...
JavaScript timers - Archive of obsolete content
functions available to workers in addition to the standard javascript set of functions (such as string, array, object, json etc), there are a variety of functions available from the dom to workers.
Enhanced Extension Installation - Archive of obsolete content
the pending operations list - a set of entries organized into arrays hashed by operation key, each entry having a locationkey and id properties.
Jetpack Processes - Archive of obsolete content
it returns an array whose elements are the return values of each receiver in the chrome process that was triggered by the message.
Listening to events in Firefox extensions - Archive of obsolete content
the filters are held in the array mfilters, the internal listeners in the array mtablisteners.
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
s; var tc = new testcase('rpn calc testcase'); var module = new modulemanager(); var rpncalc = module.require('package', 'calc'); tc.tests = { '2 1 +': function() { var calc = new rpncalc.rpncalc(); calc.init(); calc.push(2); calc.push(1); calc.plus(); assert.equals(calc.pop(), 3); } } listing 3: additional content for calc.js function rpncalc() { this.stack = new array(); } rpncalc.prototype = { init: function() { this.stack = new array(); }, push: function(val) { this.stack.push(number(val)); }, _letfunc: function(func) { a = this.pop(); b = this.pop(); this.push(func(a, b)); }, plus: function() { return this._letfunc(this._plus); }, _plus: function(a, b) { return a + b; }, pop: function() { return this.sta...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
orient whether a box's contents will be vertically or horizontally arrayed depends on the elements in their initial state.
Adding preferences to an extension - Archive of obsolete content
com/d/quotes.csv?f=sl1d1t1c1ohgv&e=.csv&s=" + symbol; function inforeceived() { var samplepanel = document.getelementbyid('stockwatcher2'); var output = httprequest.responsetext; if (output.length) { // remove any whitespace from the end of the string output = output.replace(/\w*$/, ""); // build the tooltip string var fieldarray = output.split(","); samplepanel.label = symbol + ": " + fieldarray[1]; samplepanel.tooltiptext = "chg: " + fieldarray[4] + " | " + "open: " + fieldarray[5] + " | " + "low: " + fieldarray[6] + " | " + "high: " + fieldarray[7] + " | " + "vol: " + fieldarray[8]; } } var httprequest = new xmlhttprequest(); ...
MozAudioAvailable - Archive of obsolete content
framebuffer read only framebuffer (array) the decoded audio sample data (i.e., floats).
Localizing an extension - Archive of obsolete content
then we replace any occurrences of the literal strings with the appropriate variables: samplepanel.tooltiptext = changestring + fieldarray[4] + " | " + openstring + fieldarray[5] + " | " + lowstring + fieldarray[6] + " | " + highstring + fieldarray[7] + " | " + volumestring + fieldarray[8]; localizing the description in install.rdf see localizing extension descriptions.
Monitoring WiFi access points - Archive of obsolete content
then the loop in lines 19-22 iterates over the list of access points received in the accesspoints array and adds them to the html in the div.
HTTP Class Overview - Archive of obsolete content
rovider talks to the socket transport service feeds data to its transaction object routes progress notifications nshttpconnectioninfo identifies a connection nshttptransaction implements nsirequest encapsulates a http request and response parses incoming data nshttpchunkeddecoder owned by a transaction strips chunked transfer encoding nshttprequesthead owns a nshttpheaderarray knows how to fill a request buffer nshttpresponsehead owns a nshttpheaderarray knows how to parse response lines performs common header manipulations/calculations nshttpheaderarray stores http "<header>:<value>" pairs nshttpauthcache stores authentication credentials for http auth domains nshttpbasicauth implements nsihttpauthenticator generates basic auth credentials from...
Settings - Archive of obsolete content
the value of the settings property is an array of objects representing the settings to expose to users.
Settings - Archive of obsolete content
the value of the settings property is an array of objects representing the settings to expose to users.
Simple Storage - Archive of obsolete content
jetpack.future.import("menu");jetpack.future.import("selection");jetpack.future.import("storage.simple");// create the persistent notes array if it doesn't already exist.jetpack.storage.simple.notes = jetpack.storage.simple.notes || [];var notes = jetpack.storage.simple.notes;// updates the jetpack menu with the current notes.
Clipboard - Archive of obsolete content
jetpack.import.future("clipboard");var mycontent = "<i>this is some italic text</i>";jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()returns an array of available jetpack clipboard flavors, for the current system clipboard state.
Clipboard Test - Archive of obsolete content
jetpack.import.future("clipboard");var mycontent = "<i>this is some italic text</i>";jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()returns an array of available jetpack clipboard flavors, for the current system clipboard state.
Clipboard - Archive of obsolete content
jetpack.import.future("clipboard"); var mycontent = "<i>this is some italic text</i>"; jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()returns an array of available jetpack clipboard flavors, for the current system clipboard state.
Simple Storage - Archive of obsolete content
jetpack.future.import("menu"); jetpack.future.import("selection"); jetpack.future.import("storage.simple"); // create the persistent notes array if it doesn't already exist.
Clipboard - Archive of obsolete content
jetpack.import.future("clipboard"); var mycontent = "<i>this is some italic text</i>"; jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()returns an array of available jetpack clipboard flavors, for the current system clipboard state.
Mozilla Application Framework in Detail - Archive of obsolete content
gecko is the premier cross-platform, full-featured, mature and well-tested layout engine available, providing robust and high quality support for a massive array of standards.
Porting NSPR to Unix Platforms - Archive of obsolete content
usually <tt>jmp_buf</tt> is an array of integers, and some platforms have a <tt>jb_sp</tt> macro that tells you which array element is the stack pointer.
Tamarin build documentation - Archive of obsolete content
the builtin.abc file provides internal information about the built-in classes (object, array, etc).
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
one should be particularly cautious of arrays since they are passed by reference by default.
Writing textual data - Archive of obsolete content
os.close(); you can also write character arrays using the write function, although using writestring is simpler from javascript code.
Windows stub installer - Archive of obsolete content
finally add <component> to the component list array @gcomponentlist at: <http://lxr.mozilla.org/seamonkey/sou...makeall.pl#125> you can test it by changing your current working directory to mozilla/xpinstall/wizard/windows/builder and running "perl build.pl" on the shell prompt.
Install script template - Archive of obsolete content
utepath the fully qualified path to the xpt * @param plugindescription a string describing the plugin * @param vendor a string describing the vendor * @param productname the name of this software * @param pluginversion version string of the plugin * @param mimetype mime type handled by the plugin plugins with more than one mime type might use an array * @param suffix suffix handled by plugin (e.g.
WinRegValue - Archive of obsolete content
winregvalue.reg_dword_little_endian = 4 winregvalue.reg_dword_big_endian = 5 winregvalue.reg_link = 6 winregvalue.reg_multi_sz = 7 winregvalue.reg_resource_list = 8 winregvalue.reg_full_resource_descriptor = 9 winregvalue.reg_resource_requirements_list = 10 regdata a java byte array containing the data.
droppedLinkHandler - Archive of obsolete content
droppedlinkhandler(event, uri, name) -- firefox 51 or older droppedlinkhandler(event, links) -- firefox 52 or newer event -- drop event, or null if no event is available uri -- uri string of the dropped link name -- name string of the dropped link links -- array of the dropped items with nsidroppedlinkitem interface ...
Working With Directories - Archive of obsolete content
the following example returns an array of all of a directory's subdirectories: function getsubdirs() { var arr = []; var items = io.getfile("home", "").directoryentries; while (items.hasmoreelements()) { var item = items.getnext(); if (item.isdirectory()) arr.push(item); } return arr; } ...
appendGroup - Archive of obsolete content
the argument should be an array of objects, one for each document to load.
getElementsByAttributeNS - Archive of obsolete content
« xul reference home getelementsbyattributens(ns, attrib, value ) return type: dom nodelist returns an array of all the child elements of the element that have the attribute namespace given by the first argument, the attribute name given by the second argument, and the value given by the third argument.
getFormattedString - Archive of obsolete content
« xul reference home getformattedstring( key, strarray ) return type: string looks up the format string for the given key name in the string bundle and returns a formatted copy where each occurrence of %s (uppercase) is replaced by each successive element in the supplied array.
loadGroup - Archive of obsolete content
the argument should be an array of objects, one for each document to load.
loadTabs - Archive of obsolete content
« xul reference home loadtabs( uris, loadinbackground, replace ) loadtabs( uris, params ) return type: no return value loads a set of uris, specified by the array uris, into tabs.
showOnlyTheseTabs - Archive of obsolete content
« xul reference home showonlythesetabs( atabs ) return type: no return value makes all tabs in the atabs array visible, and all other tabs hidden.
children - Archive of obsolete content
« xul reference children type: array of elements returns the list of items in the richlistbox.
externalToolbars - Archive of obsolete content
« xul reference externaltoolbars type: array of elements an array of external toolbars; that is, toolbar elements that should be considered to be members of this toolbox, even if they are not actually children of the toolbox.
selectedItems - Archive of obsolete content
« xul reference selecteditems type: array of listitems returns an array of the selected items in the list.
tabbrowser.tabs - Archive of obsolete content
« xul reference tabs type: array a nodelist containing the tab objects for each tab in the tabbrowser.
visibleTabs - Archive of obsolete content
« xul reference visibletabs type: array an array containing tab objects for each visible tab in the tabbrowser.
Tree Widget Changes - Archive of obsolete content
to get a column in javascript: tree.columns.getcolumnfor(treecolelement); tree.columns.getnamedcolumn(treecolid); tree.columns.getcolumnat(index); you can also just use array syntax to get a column: tree.columns["lastname"]; tree.columns[5]; once you have a column, you can get various properties of it: column.index - the index of the column in displayed order column.id - the id attribute of the column column.element - the treecol element column.x - the x position in the tree of the left edge of the column column.width - the width of the column in c++ code,...
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
the code works as follows: this.clipboard=document.getanonymousnodes(this)[0].value; the first element of the anonymous content array is retrieved which gives a reference to the textbox element, which happens to be the first (and only) element within the content element.
Creating Dialogs - Archive of obsolete content
these arguments are passed to the new dialog and placed in an array stored in the new window's arguments property.
Creating an Installer - Archive of obsolete content
next, we create an array xpi which will hold the name (calendar) and url (calendar.xpi) of the installer.
Document Object Model - Archive of obsolete content
we then use a for loop to iterate over the children, accessing each item using an array-like notation.
Manipulating Lists - Archive of obsolete content
the first selected item is always retrieved as the size of the array will decrease as the items are removed.
Trees - Archive of obsolete content
ArchiveMozillaXULTutorialTrees
if you do, you might store the data in an array or javascript data structure, or load the data from an xml file.
XPCOM Interfaces - Archive of obsolete content
the classes property is an array of all of the available components.
The Implementation of the Application Object Model - Archive of obsolete content
an incredible array of features would be lost.
browser - Archive of obsolete content
droppedlinkhandler(event, uri, name) -- firefox 51 or older droppedlinkhandler(event, links) -- firefox 52 or newer event -- drop event, or null if no event is available uri -- uri string of the dropped link name -- name string of the dropped link links -- array of the dropped items with nsidroppedlinkitem interface homepage type: url this attribute allows you to set a homepage for the browser element.
listbox - Archive of obsolete content
selecteditems type: array of listitems returns an array of the selected items in the list.
richlistbox - Archive of obsolete content
selecteditems type: array of listitems returns an array of the selected items in the list.
stringbundle - Archive of obsolete content
methods getformattedstring( key, strarray ) return type: string looks up the format string for the given key name in the string bundle and returns a formatted copy where each occurrence of %s (uppercase) is replaced by each successive element in the supplied array.
tree - Archive of obsolete content
ArchiveMozillaXULtree
e of the id attribute for each of the selected rows of a tree: var idlist = []; var rangecount = tree.view.selection.getrangecount(); for (var i = 0; i < rangecount; i++) { var start = {}; var end = {}; tree.view.selection.getrangeat(i, start, end); for (var c = start.value; c <= end.value; c++) { idlist.push(tree.view.getitematindex(c).firstchild.id); } } the following returns a array of the indicies of the rows where the value is checked in a checkbox type column: function getcellchecked(tree, columnid) { var arr = []; var column = tree.columns.getnamedcolumn(columnid); for (var i = 0; i < tree.view.rowcount; i++) { if (tree.view.getcellvalue(i, column) == 'true') arr.push(i); } return arr; } to get the text value for a specific column (for example colu...
Deploying XULRunner - Archive of obsolete content
.yourapplication</string> <key>cfbundleinfodictionaryversion</key> <string>6.0</string> <key>cfbundlename</key> <string>applicationname</string> <key>cfbundlepackagetype</key> <string>appl</string> <key>cfbundleshortversionstring</key> <string>1.0</string> <key>cfbundlesignature</key> <string>????</string> <!--only useful if your app handle urls--> <key>cfbundleurltypes</key> <array> <dict> <key>cfbundleurliconfile</key> <string>app_icon.icns</string> <key>cfbundleurlname</key> <string>yourapp entity</string> <key>cfbundleurlschemes</key> <array> <string>chrome</string> </array> </dict> </array> <key>cfbundleversion</key> <string>1.0</string> </dict> </plist> here's a sample of the pkginfo file aapl????
2006-11-10 - Archive of obsolete content
build problem firefox 2.0 on fc3 november 10th: vin downloaded the latest firefox 2 rc3 and tried to build it on fc3 with the following options: ./configure --enable-application=browser --prefix=$prefix --enable-extensions=default,spatialnavigation then he tried running "make" and received the following error: /usr/bin/ld: testtarray.o(.text+0x2237): unresolvable relocation against symbol `nstarray_base::semptyhdr' /usr/bin/ld: final link failed: nonrepresentable section on output collect2: ld returned 1 exit status gmake[3]: *** [testtarray] error 1 gmake[3]: leaving directory `/usr/mozilla2/src/mozilla/xpcom/tests' gmake[2]: *** [libs] error 2 gmake[2]: leaving directory `/usr/mozilla2/src/mozilla/xpcom' gmake[1]: *** [tier...
2006-11-17 - Archive of obsolete content
recycle array objects a user trying to overcome the need of using huge number of arrays (as vectors) asks if its possible to reuse unreferenced array objects instead of create new ones in spidermonkey.
External resources for plugin creation - Archive of obsolete content
feature highlights include thread safety checks, unicode support (with std::wstring), activex support, built-in drawing model negotiation for mac, automatic type conversion (including javascript arrays and objects), advanced security features, and more.
NPString - Archive of obsolete content
syntax typedef struct _npstring { const nputf8 *utf8characters; uint32_t utf8length; } npstring; fields the data structure has the following fields: utf8characters an array of the utf-8 characters comprising the string.
NPAPI plugin reference - Archive of obsolete content
npn_getstringidentifiers returns an array of opaque identifiers for the names that are passed in.
The Basics of Web Services - Archive of obsolete content
an example is, it is easier to send a multi-dimensional array with soap rather then with xml-rpc.
Accessing XML children - Archive of obsolete content
the xml list behaves much like an array.
Iterator - Archive of obsolete content
iterator instance returns [property_name, property_value] array for each iteration if keyonly is falsy, otherwise, if keyonly is truthy, it returns property_name for each iteration.
Expression closures - Archive of obsolete content
examples a shorthand for binding event listeners: document.addeventlistener('click', function() false, true); using this notation with some of the array functions from javascript 1.6: elems.some(function(elem) elem.type == 'text'); ...
Microsoft JavaScript extensions - Archive of obsolete content
objects activexobject debug enumerator vbarray functions getobject scriptengine scriptenginebuildversion scriptenginemajorversion scriptengineminorversion statements @cc-on @if @set other date.getvardate() error.description error.number error.stacktracelimit ...
New in JavaScript 1.1 - Archive of obsolete content
--> new features in javascript 1.1 new objects array boolean function number new properties number.max_value number.min_value nan number.negative_infinity number.positive_infinity new methods array.prototype.join() array.prototype.reverse() array.prototype.sort() array.prototype.split() new operators typeof void other new features <noscript> liveconnect.
New in JavaScript 1.8.1 - Archive of obsolete content
new features in javascript 1.8.1 object.getprototypeof() support for native json string.prototype.trim() string.prototype.trimleft() string.prototype.trimright() changed functionality in javascript 1.8.1 implicit setting of properties in object and array initializers no longer execute setters in javascript.
ECMAScript 5 support in Mozilla - Archive of obsolete content
added in javascript 1.6 (gecko 1.8, firefox 1.5) new array methods offering several improved methods for manipulating arrays -- have been part of javascript since javascript 1.6.
for each...in - Archive of obsolete content
examples using for each...in warning: never use a loop like this on arrays.
LiveConnect Reference - Archive of obsolete content
java-to-javascript global objects java packages netscape sun javaarray javaclass javaobject javapackage ...
LiveConnect - Archive of obsolete content
the reimplementation also restores the ability to use try-catch exceptions within javascript, and is free of the increasing number of other bugs introduced by the decline of the original liveconnect (e.g., java.lang.string and arrays not working properly).
JavaClass - Archive of obsolete content
example in the following example, the javaclass object java.lang.string is passed as an argument to the newinstance method which creates an array: var cars = java.lang.reflect.array.newinstance(java.lang.string, 15); see also javaarray, javaobject, javapackage, packages ...
JavaObject - Archive of obsolete content
var thestring = new java.lang.string("hello, world"); thestring.getclass(); // returns java.lang.string see also javaarray, javaclass, javapackage, packages ...
JavaPackage - Archive of obsolete content
the following code creates the javapackage red: var red = packages.redwood; see also javaarray, javaclass, javaobject, packages ...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
ensure the server-side function name is contained within the jaxer.proxies array.
Displaying a graphic with audio samples - Archive of obsolete content
a() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; fft = new fft(framebufferlength / channels, rate); } function audioavailable(event) { var fb = event.framebuffer, t = event.time, /* unused, but it's there */ signal = new float32array(fb.length / channels), magnitude; for (var i = 0, fbl = framebufferlength / 2; i < fbl; i++ ) { // assuming interlaced stereo channels, // need to split and merge into a stero-mix mono signal signal[i] = (fb[2*i] + fb[2*i+1]) / 2; } // clear the canvas before drawing spectrum ctx.fillstyle = "rgb(0,0,0)"; ctx.fil...
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
ns_imethod getinterfaces(pruint32 *count, nsiid * **array) {return ns_error_not_implemented;} ns_imethod gethelperforlanguage(pruint32 language, nsisupports **_retval) {return ns_error_not_implemented;} ns_imethod getcontractid(char * *acontractid) {return ns_error_not_implemented;} ns_imethod getclassdescription(char * *aclassdescription) {return ns_error_not_implemented;} ns_imethod getclassid(nscid * *aclassid) {return ns_...
Introduction to game development for the Web - Game development
typed arrays javascript typed arrays give you access to raw binary data from within javascript; this lets you manipulate gl textures, game data, or anything else, even if it's not in a native javascript format.
WebVR — Virtual Reality for the Web - Game development
es[i]; break; } } if (ghmd) { for (var i = 0; i < devices.length; ++i) { if (devices[i] instanceof positionsensorvrdevice && devices[i].hardwareunitid === ghmd.hardwareunitid) { gpositionsensor = devices[i]; break; } } } }); this code will loop through the available devices and assign proper sensors to the headsets — the first devices array contains the connected devices, and a check is done to find the hmdvrdevice, and assign it to the ghmd variable — using this you can set up the scene, getting the eye parameters, setting the field of view, etc.
Audio for Web games - Game development
const trackels = document.queryselectorall('li'); we want to make sure each file has loaded and been decoded into a buffer before we use it, so let's create an async function to allow us to do this: async function getfile(filepath) { const response = await fetch(filepath); const arraybuffer = await response.arraybuffer(); const audiobuffer = await audioctx.decodeaudiodata(arraybuffer); return audiobuffer; } we can then use the await operator when calling this function, which ensures that we can run subsequent code when it has finished executing.
Expando - MDN Web Docs Glossary: Definitions of Web-related terms
expando properties are properties added to dom nodes with javascript, where those properties are not part of the object's dom specification: window.document.foo = 5; // foo is an expando the term may also be applied to properties added to objects without respecting the object's original intent, such as non-numeric named properties added to an array.
JSON - MDN Web Docs Glossary: Definitions of Web-related terms
json can represent numbers, booleans, strings, null, arrays (ordered sequences of values), and objects (string-value mappings) made up of these values (or of other arrays and objects).
Mutable - MDN Web Docs Glossary: Definitions of Web-related terms
in javascript, only objects and arrays are mutable, not primitive values.
Python - MDN Web Docs Glossary: Definitions of Web-related terms
it was created by guido van rossum as a successor to another language (called abc) between 1985 and 1990, and is currently used on a large array of domains like web development, desktop applications, data science, devops, and automation/productivity.
Serialization - MDN Web Docs Glossary: Definitions of Web-related terms
in an array buffer or file format).
Signature (functions) - MDN Web Docs Glossary: Definitions of Web-related terms
the method accepts one parameter of type string array.
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
examples of well-known symbols are: symbol.iterator for array-like objects, or symbol.search for string objects.
Web standards - MDN Web Docs Glossary: Definitions of Web-related terms
which among other things govern set-up and use of uris, http, and mime w3c: specifications for markup language (e.g., html), style definitions (i.e., css), dom, accessibility iana (internet assigned numbers authority): name and number registries ecma intl.: scripting standards, most prominently for javascript iso (international organization for standardization): standards governing a diverse array of aspects, including character encodings, website management, and user-interface design learn more general knowledge web standards on wikipedia ...
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
napshotlength; k++) { a[k] = xpathresult.snapshotitem(k); } responsenodes = a; } else { // otherwise, the response must be a single well-formed document response responsenodes = [response.documentelement]; // put in array so can be treated the same way as the above } // prepend any node(s) (as xml) then remove xinclude for (j=0; j < responsenodes.length ; j++) { xincludeparent.insertbefore(responsenodes[j], xinclude); } xincludeparent.removechil...
MDN Web Docs Glossary: Definitions of Web-related terms
glossary of terms a abstraction accessibility accessibility tree (aom) adobe flash ajax algorithm alignment container alignment subject alpha (alpha channel) alpn api apple safari application context argument aria arpa arpanet array ascii asynchronous atag attribute b bandwidth base64 baseline beacon bézier curve bidi bigint blink block block (css) block (scripting) block cipher mode of operation boolean boot2gecko bootstrap boundi...
Practical positioning examples - Learn web development
when run, the function is passed a reference to the particular tab it is being run for, and an index number i that indentifies the tab's position in the tabs array.
What are browser developer tools? - Learn web development
you can expand the list to view the values in the array.
Example 3 - Learn web development
.4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { if (select.cl...
Example 4 - Learn web development
.4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { if (select.cl...
Example 5 - Learn web development
.4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #ffffff; } javascript content // ------- // // helpers // // ------- // nodelist.prototype.foreach = function (callback) { array.prototype.foreach.call(this, callback); } // -------------------- // // function definitions // // -------------------- // function deactivateselect(select) { if (!select.classlist.contains('active')) return; var optlist = select.queryselector('.optlist'); optlist.classlist.add('hidden'); select.classlist.remove('active'); } function activeselect(select, selectlist) { if (select.cl...
Sending forms through JavaScript - Learn web development
let's look at an example: <button>click me!</button> and now the javascript: const btn = document.queryselector('button'); function senddata( data ) { console.log( 'sending data' ); const xhr = new xmlhttprequest(); let urlencodeddata = "", urlencodeddatapairs = [], name; // turn the data object into an array of url-encoded key/value pairs.
Getting started with the Web - Learn web development
if you're just starting out, you might be confused by the array of code editors, frameworks, and testing tools out there.
Making asynchronous programming easier with async and await - Learn web development
see the promise.all() line: let values = await promise.all([coffee, tea, description]); by using await here we are able to get all the results of the three promises returned into the values array, when they are all available, in a way that looks very much like sync code.
Choosing the right approach - Learn web development
ment('img'); image1.src = objecturl1; image2.src = objecturl2; document.body.appendchild(image1); document.body.appendchild(image2); // display the text in a paragraph let para = document.createelement('p'); para.textcontent = desctext; document.body.appendchild(para); }); pitfalls if a promise.all() rejects, then one or more of the promises you are feeding into it inside its array parameter must be rejecting, or might not be returning promises at all.
A first splash into JavaScript - Learn web development
troubleshooting javascript storing the information you need — variables basic math in javascript — numbers and operators handling text — strings in javascript useful string methods arrays assessment: silly story generator ...
Basic math in JavaScript — numbers and operators - Learn web development
troubleshooting javascript storing the information you need — variables basic math in javascript — numbers and operators handling text — strings in javascript useful string methods arrays assessment: silly story generator ...
Handling text — strings in JavaScript - Learn web development
troubleshooting javascript storing the information you need — variables basic math in javascript — numbers and operators handling text — strings in javascript useful string methods arrays assessment: silly story generator ...
Inheritance in JavaScript - Learn web development
whenever you use various features of a web api , or methods/properties defined on a built-in browser object that you call on your strings, arrays, etc., you are implicitly using inheritance.
Object-oriented JavaScript for beginners - Learn web development
and the bio only includes two interests, even if more are listed in the interests array.
Object prototypes - Learn web development
you'll see other examples of prototype chain inheritance all over javascript — try looking for the methods and properties defined on the prototype of the string, date, number, and array global objects, for example.
Introducing JavaScript objects - Learn web development
in javascript, most things are objects, from core javascript features like arrays to the browser apis built on top of javascript.
Introduction to client-side frameworks - Learn web development
let's say that our state is an array of objects structured like this: const state = [ { id: 'todo-0', name: 'learn some frameworks!' } ] how do we show one of those tasks to our user?
React resources - Learn web development
this screenshot shows our finished application as it appears in react devtools: on the left, we see all of the components that make up our application, including some unique keys for the things that are rendered from arrays.
Beginning our React todo list - Learn web development
we have an array of buttons that will be used to filter our tasks.
Componentizing our Svelte app - Learn web development
in its <script> section, add this handler: function updatetodo(todo) { const i = todos.findindex(t => t.id === todo.id) todos[i] = { ...todos[i], ...todo } } we find the todo by id in our todos array, and update its content using spread syntax.
Using Vue computed properties - Learn web development
in our case, this would only re-run when the todoitems array changes.
Understanding client-side JavaScript frameworks - Learn web development
we will learn how to deal with reactivity issues related to updating objects and arrays.
Handling common JavaScript problems - Learn web development
typed arrays allow javascript code to access and manipulate raw binary data, which is necessary as browser apis for example start to manipulate streams of raw video and audio data.
Software accessibility: Where are we today?
the optacon provides access to printed words, graphics and on-screen information by means of an array vibrating pins the size of an index finger.
Theme concepts
however, noting that "frame": and "tab_background_text": only support rgb color array definition on chrome.
Error codes returned by Mozilla APIs
0x8057001a) ns_error_xpc_js_threw_native_object (0x8057001b) ns_error_xpc_js_threw_js_object (0x8057001c) ns_error_xpc_js_threw_null (0x8057001d) ns_error_xpc_js_threw_string (0x8057001e) ns_error_xpc_js_threw_number (0x8057001f) ns_error_xpc_javascript_error (0x80570020) ns_error_xpc_javascript_error_with_details (0x80570021) ns_error_xpc_cant_convert_primitive_to_array (0x80570022) ns_error_xpc_cant_convert_object_to_array (0x80570023) ns_error_xpc_not_enough_elements_in_array (0x80570024) ns_error_xpc_cant_get_array_info (0x80570025) ns_error_xpc_not_enough_chars_in_string (0x80570026) ns_error_xpc_security_manager_veto (0x80570027) ns_error_xpc_interface_not_scriptable (0x80570028) ns_error_xpc_interface_not_from_nsisupports (0x805...
Limitations of frame scripts
examples of apis add-on authors should avoid in frame scripts: nsifileinputstream nsifileoutputstream constructing a file from a string or nsifile (but file objects can be sent via message manager) htmlinputelement.mozsetfilenamearray (alternative: mozsetfilearray) xul and browser ui anything that tries to touch the browser ui or anything to do with xul is likely to not work in the content process.
Limitations of frame scripts
for example: nsifileinputstream nsifileoutputstream constructing a file from a string or nsifile (but file objects can be sent via message manager) htmlinputelement.mozsetfilenamearray (alternative: mozsetfilearray) file: uris, see bug 1187099 <...> xul and browser ui anything that tries to touch the browser ui or anything to do with xul is likely not to work in the content process.
Script security
expanded principal an expanded principal is specified as an array of origins: ["http://mozilla.org", "http://moz.org"] the expanded principal subsumes every content principal it contains.
How Mozilla determines MIME Types
unknown decoder located at netwerk/streamconv/converters/nsunknowndecoder.cpp, the interesting part starts at line 287, the ssnifferentries array together with the determinecontenttype function.
IPDL Type Serialization
g, void** aiter, paramtype* aresult) { if (!readparam(amsg, aiter, &(aresult->i)) || !readparam(amsg, aiter, &(aresult->j))) return false; for (int i = 0; i < 4; ++i) if (!readparam(amsg, aiter, &(aresult->k[i]))) return false; return true; } }; } // namespace ipc once you have a serializer for a type, you can serialize a collection of it (ex: an nstarray<examplestruct>) by simply declaring "using nstarray<examplestruct>;' in your ipdl file, then using it in a ipc method.
JavaScript Tips
references this was started as a reprint of neil's guide some more current info on this blog post how to remove duplicate objects from an array javascript ...
AddonListener
only applies to the following properties: applybackgroundupdates void onpropertychanged( in addon addon, in string properties[] ) parameters addon the addon that has had its properties changed properties an array of the names of properties that changed.
UpdateCheckListener
void onupdatecheckcomplete( in updateinfo results[] ) parameters results an array of updateinfo objects representing the available add-on versions onupdatecheckerror() called when the update check fails.
UpdateInfo
each item in the array contains "id", "minversion", and "maxversion" properties.
Add-on Repository
the api also offers two ways to search for and retrieve an array of addon instances: retrieverecommendedaddons(), which returns a list of recommended add-ons, and searchaddons(), which performs a search of the repository.
PopupNotifications.jsm
secondaryactions an array of notification action objects; these are used to populate the drop-down menu on the notification panel's button.
Promise
{{private:handlers}}: array of objects holding references to functions registered by the then() method, for pending promises only.
Using JavaScript code modules
the module also defines a special array named exported_symbols.
Mozilla Framework Based on Templates (MFBT)
this pointer is a useful way to expose access to values within an array.
MathML Demo: <mo> - operator, fence, separator, or accent
this problem can be solved using aligned arrays, as follows a b c d ⁢ a b c d however, all reasonable attempts to fence the column vector will fail because latex fences are symmetric.
MathML Demo: <mtable> - tables and matrices
math axis test, using externally aligned arrays inside symmetric fences.
Investigating leaks using DMD heap scan mode
block_analyzer.py will return a series of entries that look like this (with the [...] indicating where i have removed things): 0x7f089306b000 size = 4096 bytes at byte offset 2168 nsattrandchildarray::growby[...] nsattrandchildarray::insertchildat[...] [...] 0x7f089306b000 is the address of the block that contains $leakaddr.
DMD
once-reported (59.18% cumulative) allocated at { #01: (no stack trace recorded due to --stacks=partial) } reported at { #01: mozilla::dmd::dmdfuncs::report(void const*) (/home/njn/moz/mi5/go64dmd/memory/replace/dmd/../../../../memory/replace/dmd/dmd.cpp:1646) #02: windowsmallocsizeof(void const*) (/home/njn/moz/mi5/dom/base/nswindowmemoryreporter.cpp:189) #03: nsattrandchildarray::sizeofexcludingthis(unsigned long (*)(void const*)) const (/home/njn/moz/mi5/dom/base/nsattrandchildarray.cpp:880) #04: mozilla::dom::fragmentorelement::sizeofexcludingthis(unsigned long (*)(void const*)) const (/home/njn/moz/mi5/dom/base/fragmentorelement.cpp:2337) #05: nsinode::sizeofincludingthis(unsigned long (*)(void const*)) const (/home/njn/moz/mi5/go64dmd/parser/html/../../../dom...
Memory reporting
nstarray and nsthashtable.
TraceMalloc
tracemallocchangelogfd(logfd) - change the current log file to the one identified by logfd, returning the previous fd (so you can maintain a number of open files; keep their fds in a js array!).
PRAddrInfo
a structure containing an array of prnetaddr structures.
PRIPv6Addr
pripv6addr is always manipulated as a byte array.
PR_FreeLibraryName
syntax #include <prlink.h> void pr_freelibraryname(char *mem); parameters the function has this parameter: mem a reference to a character array that was previously allocated by the dynamic library runtime.
PR_GetErrorText
syntax #include <prerror.h> print32 pr_geterrortext(char *text); parameters the function has one parameter: text on output, the array pointed to contains the thread's current error text.
PR_Initialize
argv the base address of an array of strings that compromise the program's argument vector.
PR_LoadLibrary
syntax #include <prlink.h> prlibrary* pr_loadlibrary(const char *name); parameters the function has this parameter: name a platform-dependent character array that names the library to be loaded, as returned by pr_getlibraryname.
PR_SetLibraryPath
syntax #include <prlink.h> prstatus pr_setlibrarypath(const char *path); parameters the function has this parameter: path a pointer to a character array that contains the directory path that the application should use as a default.
Certificate functions
mxr 3.10 and later cert_decodeocspresponse mxr 3.6 and later cert_decodeoidsequence mxr 3.2 and later cert_decodeprivkeyusageperiodextension mxr 3.10 and later cert_decodetruststring mxr 3.4 and later cert_decodeusernotice mxr 3.2 and later cert_dernametoascii mxr 3.4 and later cert_destroycertarray mxr 3.2 and later cert_destroycertificate mxr 3.2 and later cert_destroycertificatelist mxr 3.2 and later cert_destroycertificatepoliciesextension mxr 3.2 and later cert_destroycertificaterequest mxr 3.2 and later cert_destroycertlist mxr 3.2 and later cert_destroyname mxr 3.2 and later cert_d...
Cryptography functions
3.2 and later pk11_getbestslotmultiple mxr 3.2 and later pk11_getbestwrapmechanism mxr 3.2 and later pk11_getblocksize mxr 3.2 and later pk11_getcertfromprivatekey mxr 3.9.3 and later pk11_getcurrentwrapindex mxr 3.2 and later pk11_getdefaultarray mxr 3.8 and later pk11_getdefaultflags mxr 3.8 and later pk11_getdisabledreason mxr 3.8 and later pk11_getfirstsafe mxr 3.2 and later pk11_getinternalkeyslot mxr 3.2 and later pk11_getinternalslot mxr 3.2 and later pk11_getkeygen ...
JSS FAQ
MozillaProjectsNSSJSSJSS FAQ
import java.io.bytearrayinputstream; [...] certificate cert = (certificate) asn1util.decode( certificate.gettemplate(),x509cert.getencoded() ); how do i convert org.mozilla.jss.pkix.cert to org.mozilla.jss.crypto.x509certificate?
NSS 3.15.5 release notes
notable changes in nss 3.15.5 bug 950129: improve the ocsp fetching policy when verifying ocsp responses bug 949060: validate the iov input argument (an array of priovec structures) of ssl_writev (called via pr_writev).
NSS 3.20 release notes
the current implementation of nss will always use the first entry in the array that is passed as a parameter to the ssl_dhegroupprefset api.
nss tech note2
display verbose information, including template values, array values, etc.
nss tech note4
the oid data structure contains an array of identifier bytes (each byte is a "level" in a hierarchical namespace), a text description, and some other things.
FC_GetOperationState
poperationstate [out] pointer to a byte array of a length sufficient for containing the operation state or null.
FC_GetSlotList
pslotlist [out] either null or a pointer to an existing array of ck_slot_id objects.
NSS_3.12.3_release_notes.html
bug 464406: fix signtool regressions bug 465270: uninitialised value in devutil.c::create_object() bug 465273: dead assignment in devutil.c::nssslotarray_clone() bug 465926: during import of pkcs #12 files bug 466180: ssl_configmpserversidcache with default parameters fails on {net bug 466194: cert_decodetruststring should take a const char * input trusts string.
Necko walkthrough
note: nsconnectionentry has a single nshttpconnectioninfo object attached, a pending queue of nshttptransactions, and 3 arrays for connections: active nshttpconnections idle nshttpconnections nshalfopensockets nshttpconnectionmgr::trydispatchtransaction there is a series of decisions about whether dispatchtransaction is called, along with good code comments: best to read the code for more detail.
Rhino Examples
the matrix class - implementing scriptable matrix.java provides a simple multidimensional array by implementing the scriptable interface.
The JavaScript Runtime
however, this is not the implementation used in practice because a number to string conversion is too expensive to be performed on every array access.
Rhino serialization
(it might be possible to save the java bytecodes in an array and then load the class upon deserialization, but at best that would eat up a lot of memory for just this feature.) one way around this is to compile the functions using the jsc tool: $ cat f.js function f() { return 3; } $ java -classpath js.jarorg.mozilla.javascript.tools.jsc.main f.js $ cat test2.js loadclass("f"); serialize(f, "f.ser"); g = deserialize("f.ser"); print(g()); $ java -classpath ...
FOSS
bundled modules include support for bytearray, bytestring, cgi, posix signals, ffi, and more.
GCIntegration - SpiderMonkey Redirect 1
we will need to handle pointers to array slots and string characters specially, since those may actually be pointers into the middle of gc things (inline slots or inline chars).
Bytecodes
bytecodes can reference atoms and objects (typically by array index) which are also contained in the jsscript data structure.
Introduction to the JavaScript shell
if type is "binary" returns an uint8array, otherwise returns an utf-8 decoded string.
JS::Add*Root
vp/rp is the address of a c/c++ variable (or field, or array element) of type js::value, jsstring *, jsobject *, or jsscript *.
JS::CallArgs
(2nd argument of jsnative) vp js::value * a pointer to the argument value array.
JS::CompileFunction
nargs is the number of arguments the function takes, and argnames is a pointer to the first element of an array of names to assign each argument.
JS::NewFunctionFromSpec
unlike js_definefunctions, this does not treat fs as an array.
JS::SourceBufferHolder
rules for use: the data array must be allocated with js_malloc or js_realloc if ownership is being granted to the sourcebufferholder.
JS::Value
a c++ variable of type js::value represents a value in javascript: a string, number, object (including arrays and functions), boolean, symbol, null, or undefined.
JSAutoByteString
methods method description void initbytes(char *bytes) take ownership of the given byte array.
JSConstDoubleSpec
jsprop_index: property is actually an array element.
JSEnumerateOp
description jsenumerateop is called just before an object is enumerated (via a for...in statement, an array comprehension, or a call to js_enumerate).
JSExtendedClass.wrappedObject
a wrapper object that wraps an array is considered an array for the purpose of array.prototype.concat and array.concat (which treat array arguments differently from other arguments, per ecma 262-3 §15.4.4.4).
JSFastNative
this points to element 0 of an array of argc jsvals, the arguments supplied by the caller.
JSNewEnumerateOp
id array to populate with all property keys.
JSPropertyOp
this ecmascript incompatibility is observable when assigning to the length property of an array, for example.
JSPropertySpec
to define an array of jspropertyspec, use js_psg, js_psgs, js_self_hosted_get, js_self_hosted_getset, and js_ps_end see also mxr id search for jspropertyspec jsfunctionspec jsnativewrapper js_defineproperties js_psg js_psgs js_self_hosted_get js_self_hosted_getset js_ps_end bug 766448 - changed type of getter and setter to wrapper bug 938728 - added selfhostedgetter and selfhostedsetter bug 958262 - ch...
JSString
conceptually, a javascript string is just an array of char16_t characters and a length.
JSVAL_TO_STRING
(the difference is that the latter will convert an object, array, number, or other value to a string in a type-safe way, creating a new string if needed.) to convert the return type of this macro (jsstring *) to a char pointer, use js_getstringbytes.
JS_Add*Root
vp/spp/opp/rp is the address of a c/c++ variable (or field, or array element) of type jsstring *, jsobject *, or jsval.
JS_AliasProperty
creating an alias does not change the length of the property array.
JS_ClearNonGlobalObject
to remove a single array object element, use js_deleteelement.
JS_ClearScope
to remove a single array object element, use js_deleteelement.
JS_CompileFunction
nargs is the number of arguments the function takes, and argnames is a pointer to the first element of an array of names to assign each argument.
JS_CompileFunctionForPrincipals
nargs is the number of arguments the function takes, and argnames is a pointer to the first element of an array of names to assign each argument.
JS_ConvertArgumentsVA
obsolete since jsapi 30 format const char * character array containing the recognized format to which to convert.
JS_DefineElement
see also mxr id search for js_defineelement js_defineconstdoubles js_definefunction js_definefunctions js_defineobject js_defineproperties js_defineproperty js_definepropertywithtinyid js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setelement bug 959787 - changed parameter types ...
JS_DeleteElement
to truncate an array, use js_setarraylength.
JS_EncodeStringToBuffer
description js_encodestringtobuffer converts the specified javascript str to a c string (an array of 8-bit chars) and fills the specified buffer with up to length bytes of the string.
JS_ExecuteScript
obsolete since jsapi 39 obj must not be an array, an e4x xml object, a with object, or a proxy.
JS_ExecuteScriptVersion
obj must not be an array, an e4x xml object, a with object, or a proxy.
JS_FS
description use these macros to define an array of jsfunctionspecs to pass to js_definefunctions or js_initclass.
JS_GetElement
see also mxr id search for js_getelement js_defineelement js_deleteelement js_getarraylength js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement ...
JS_GetFunctionFlags
jsfun_generic_native the function is an array generic, such as array.map.
JS_GetProperty
for many objects, including objects of standard classes such as object and array, this hook does nothing and returns true, so the property get succeeds and undefined is left in *vp.
JS_GetReservedSlot
they cannot be returned from functions, set as properties on objects, embedded in javascript arrays, and so on.) new objects' reserved slots are initialized to undefined.
JS_GetStringLength
this is the same as the length of the array returned by js_getstringchars, in char16_ts (not bytes).
JS_InitStandardClasses
these include all the standard ecmascript global properties defined in ecma 262-3 §15.1: array, boolean, date, decodeuri, decodeuricomponent, encodeuri, encodeuricomponent, error, eval, evalerror, function, infinity, isnan, isfinite, math, nan, number, object, parseint, parsefloat, rangeerror, referenceerror, regexp, string, syntaxerror, typeerror, undefined, and urierror as well as a few spidermonkey-specific globals, depending on compile-time options: escape, unescape, uneval, inter...
JS_InternString
s const char * or const char16_t * pointer to a character array containing the data for the string.
JS_LookupElement
see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_newarrayobject js_setarraylength js_setelement bug 1094176 ...
JS_LookupProperty
jsresolve_classname search for the initial value of a standard class such as object, array, or error.
JS_MakeStringImmutable
applications must call js_makestringimmutable before sharing a jsstring among threads by storing it in a c/c++ variable, field, or array element that another thread can read.
JS_NewObject
see also mxr id search for js_newobject mxr id search for js_newobjectwithgivenproto js_newglobalobject js_newarrayobject js_valuetoobject bug 408871 bug 1136906, bug 1136345 -- remove parent parameter bug 1125567 -- change prototype lookup behaviour ...
JS_NewRegExpObject
i jsreg_glob global execution, creates array of matches.
JS_ReportOutOfMemory
when a script tries to grow an array beyond 230-1 elements, for example, or concatenate strings such that the result is more than 229-1 characters long, the javascript engine reports an error as though by calling this function.
JS_SET_TRACING_DETAILS
when printer is null, arg must be const char * or char * c string naming the reference and index must be either (size_t)-1 indicating that the name alone describes the reference or it must be an index into some array vector that stores the reference.
JS_SetElement
obj js::handleobject the object to modify, commonly an array object.
JS_SetPropertyAttributes
jsprop_index property is actually an index into an array of properties, and is cast to a const char *.
JS_THREADSAFE
use js_writestructuredclone to transform data into a flat array of bytes that can be safely written to disk, sent to another process or even another machine, or just passed to another thread.
JS_ValueToId
index uint32_t an unsigned integer index of array to convert.
JS_ValueToInt32
js::toint32 will also convert nan (and anything that converts to nan, such as an array of strings) to 0, whereas this routine would report an error.
SpiderMonkey 24
new c apis js_getarrayprototype provides access to the original value of array.prototype.
SpiderMonkey 45
(bug 1178581) js_internstringn renamed to js_atomizeandpinstringn (bug 1178581) js_internstring renamed to js_atomizeandpinstring (bug 1178581) js_internucstringn renamed to js_atomizeandpinucstringn (bug 1178581) js_internucstring renamed to js_atomizeandpinucstring (bug 1178581) deleted apis js_getcompartmentstats js_seticumemoryfunctions js_isgcmarkingtracer js_ismarkinggray js_idarraylength js_idarrayget js_destroyidarray js_defaultvalue js_getparent js_setparent js::parsepropertydescriptorobject js_deleteproperty2 js_deletepropertybyid2 js_deleteucproperty2 js_deleteelement2 js_newfunctionbyid js_bindcallable js_decompilefunctionbody js_getlatin1internedstringchars js_gettwobyteinternedstringchars js_newdateobjectmsec js_cleardatecaches changed apis js_i...
TPS Formdata Lists
a formdata asset list is an array of objects, each with the following properties: fieldname: required.
TPS Password Lists
a password asset list is an array of objects, each representing a stored password.
TPS Pref Lists
a prefs asset list is an array of objects with name and value keys, representing browser preferences.
TPS Tab Lists
a tabs asset list is an array of objects with the following keys: uri: the uri of the tab, required.
Animated PNG graphics
MozillaTechAPNG
the output buffer is a pixel array with dimensions specified by the width and height parameters of the png 'ihdr' chunk.
Manipulating bookmarks using Places
var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("http://google.com/", null, null); var bookmarksarray = bmsvc.getbookmarkidsforuri(uri, {}); after executing this code, the array bookmarksarray contains the ids of all bookmarks that refer to the specified uri (in this case, "http://google.com").
Places Developer Guide
get the tagging service var tagssvc = cc["@mozilla.org/browser/tagging-service;1"] .getservice(ci.nsitaggingservice); // create a uri to tag var ioservice = cc["@mozilla.org/network/io-service;1"] .getservice(ci.nsiioservice); var myuri = ioservice.newuri("http://www.mozilla.com", null, null); // tag the uri tagssvc.taguri(myuri, ["mozilla", "firefox"]); // get an array of tags for a uri var mytags = tagssvc.gettagsforuri(myuri, {}); // get an array of uris for a tag var taggeduris = tagssvc.geturisfortag("mozilla"); // get an array of all tags var arrayofalltags = tagssvc.alltags; // remove tags from a uri tagssvc.untaguri(myuri, ["mozilla", "firefox"]); this service currently integrates with and is internally dependent upon bookmarks: if you tag a ur...
Querying Places
this item is an array of folder ids from the bookmark service.
Using the Places history service
the parameters within on query as anded together as in executequery(), then the results of the different queries in the array are ored together.
extIApplication
windows readonly attribute nsivariant an array of browser windows within the application.
extIPreferenceBranch
all readonly attribute nsivariant array of extipreference listing all preferences in this branch.
Component Internals
it's tempting to reuse nsvoidarray or another publicly available class instead of writing your own linked list, but this may prove to be a fatal mistake.
Using XPCOM Components
components is the javascript object that controls the connection to components, and classes is an array of all of the classes you can ask for by contract id.
How To Pass an XPCOM Object to a New Window
to access the xpcom object from the window's code, you can access the window.arguments[] array, as shown in the example below: components.utils.reporterror(string(window.arguments[0])); this will produce output similar to "[xpconnect wrapped nsimyxpcomobject]".
Interfacing with the XPCOM cycle collector
the main macro for traverse is ns_impl_cycle_collection_traverse: ns_impl_cycle_collection_traverse(msomemember) unlink works similarly: ns_impl_cycle_collection_unlink(msomemember) these macros should handle a variety of cases, such as reference counted pointers to cycle collected nsisupports or non-nsisupports objects, as well as arrays of these pointers.
Components.Constructor
nputstream", "setinputstream"); try { // throws, because number of arguments isn't equal to the number of // arguments nsibinaryinputstream.setinputstream takes var bis = new binaryinputstream(); } catch (e) { // someinputstream is an existing nsiinputstream bis = new binaryinputstream(someinputstream); // succeeds var bytes = bis.readbytearray(somenumberofbytes); // succeeds } compare instance creation from base principles with instance creation using components.constructor(); the latter is much easier to read than the former (particularly if you're creating instances of a component in many different places): var bis = components.classes["@mozilla.org/binaryinputstream;1"] .createinstance(components.interfaces.ns...
Components.interfaces
you can retrieve an interface object using: var iface = components.interfaces.nsisupportsarray; this will return you the interface object for the nsisupportsarray interface.
Components.results
elements in this array can be used to test against unknown nsresult variables or they can be 'thrown' to indicate failure...
Components.utils.getWeakReference
and then later on it is matched in the array and used.
Components.utils
createarrayin() removed in gecko 31 returns an array created in specified compartment.
Language bindings
ide better diagnostics in the error console if not caught than simply throwing an nsresult's value will.components.idcomponents.id is a constructor that creates native objects that conform to the nsijsid interface.components.interfacescomponents.interfaces is a read-only object whose properties are interfaces indexed by their names.components.interfacesbyidcomponents.interfacesbyid is a read-only array of classes indexed by iid.components.issuccesscodedetermines whether a given xpcom return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively.components.lastresultcomponents.managercomponents.manager is a convenience reflection of the global native component manager service.
Observer Notifications
the notification's subject is an array whose first entry is the old login and whose second entry is the new one.
NS_InitXPCOM3
astaticmodules [in] an array of nsstaticmoduleinfo objects.
NS_NewLocalFile
nsembedstring is used to convert the ucs-2 character array to an object that can be passed as a const nsastring& parameter.
Append
void append( const char_type* adata, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to append to this string.
Assign
void assign( const char_type* adata, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to copy into this string.
Insert
void insert( const char_type* adata, index_type aposition, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to append to this string.
Replace
adata [in] a raw character array to append to this string.
operator=
self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string.
operator+=
self_type& operator+=( const char_type* adata ); parameters adata [in] a raw character array to append to this string.
nsACString
this class is typically used to represent ascii or utf-8 character arrays.
nsACString_internal
it represents a single contiguous array of characters, which may or may not be null-terminated.
Append
void append( const char_type* adata, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to append to this string.
Assign
void assign( const char_type* adata, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to copy into this string.
Insert
void insert( const char_type* adata, index_type aposition, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to append to this string.
Replace
adata [in] a raw character array to append to this string.
operator=
self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string.
operator+=
self_type& operator+=( const char_type* adata ); parameters adata [in] a raw character array to append to this string.
nsAString
this class is typically used to represent unicode character arrays.
nsAString_internal
it represents a single contiguous array of characters, which may or may not be null-terminated.
nsDependentCSubstring
class declaration nstdependentsubstring_chart a string class which wraps an external array of string characters.
nsDependentSubstring
class declaration nstdependentsubstring_chart a string class which wraps an external array of string characters.
nsEmbedCString
explicit nsembedcstring( const char_type* adata, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to copy into this string.
operator=
self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string.
nsEmbedString
explicit nsembedstring( const char_type* adata, size_type adatalength = pr_uint32_max ); parameters adata [in] a raw character array to copy into this string.
operator=
self_type& operator=( const char_type* adata ); parameters adata [in] a raw character array to append to this string.
amIWebInstallInfo
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void install(); attributes attribute type description installs nsivariant an array of addoninstall objects.
mozIPlaceInfo
visits mozivisitinfo[] read only: an array of mozivisitinfo objects for the place.
mozIStorageProgressHandler
mozistoragevaluearray wraps an array of sql values, such as a result row.
mozIStorageRow
last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: mozistoragevaluearray method overview nsivariant getresultbyindex(in unsigned long aindex); nsivariant getresultbyname(in autf8string aname); methods getresultbyindex() returns the value from a specific column in the row, using a zero-based index to identify the column.
GetRelations
nsiarray getrelations(); return value returns nsiarray array of accessible relations for this object, every accessible relation object implements nsiaccessiblerelation interface.
nsIAppShell
argv a direct reference to the parameter array.
nsICommandLineHandler
if this handler finds arguments that it understands, it should perform the appropriate actions (such as opening a window), and remove the arguments from the command-line array.
nsIDOMFontFaceList
nsidomfontface item( in unsigned long index ); parameters index the index into the array of the font face object to return.
nsIDOMMozNetworkStats
data nsidommoznetworkstatsdata array stats samples.
nsIDialogParamBlock
cko 1.7 method overview print32 getint( in print32 inindex ); wstring getstring( in print32 inindex ); void setint( in print32 inindex, in print32 inint ); void setnumberstrings( in print32 innumstrings ); void setstring( in print32 inindex, in wstring instring); attributes attribute type description objects nsimutablearray a place where you can store an nsimutablearray to pass nsisupports.
ExtensionManager (Toolkit)
examples here is how to retrive all the extensions installed: var em = cc['@mozilla.org/extensions/manager;1'] .getservice(ci.nsiextensionmanager); const nsiupdateitem = ci.nsiupdateitem; var extension_type = nsiupdateitem.type_extension; items = em.getitemlist(extension_type, {}); items.foreach(function(item, index, array) { alert(item.name + " / " + item.id + " version: " + item.version); }); ...
nsIFileView
selectedfiles nsiarray an nsiarray of selected files, which contains nsiarray instances.
nsIFrameMessageListener
objects unimplemented an array of cpow, or null if sync is false.
nsIINIParser
// get all sections in the ini file var sectenum = iniparser.getsections(); // save the sections in an array var sections = []; while (sectenum && sectenum.hasmore()) { var section = sectenum.getnext(); // add an array entry for each section sections.push(section); } enumerating keys this example shows how to fetch the values for all the keys in the section named "setting".
nsIMsgFilter
in nsimsgdbhdr aheader ) createaction() nsimsgruleaction nsimsgfilter::createaction ( ) getactionat() nsimsgruleaction nsimsgfilter::getactionat (in long aindex) appendaction() void nsimsgfilter::appendaction (in nsimsgruleaction action ) clearactionlist() void nsimsgfilter::clearactionlist() getsortedactionlist() void nsimsgfilter::getsortedactionlist (in nsisupportsarray actionlist) ...
nsIMsgFilterCustomAction
*/ /** * apply the custom action to an array of messages * * @param msghdrs array of nsimsgdbhdr objects of messages * @param actionvalue user-set value to use in the action * @param copylistener calling method (filtertype manual only) * @param filtertype type of filter being applied * @param msgwindow message window */ void apply(in nsiarray msghdrs /* nsimsgdbhdr array */, in autf8string ...
nsIMsgSearchCustomTerm
* * @param scope search scope (nsmsgsearchscope) * @param length object to hold array length * * @return array of operators */ void getavailableoperators(in nsmsgsearchscopevalue scope, out unsigned long length, [retval, array, size_is(length)] out nsmsgsearchopvalue operators); match /** * apply the custom search term to a message * * @param msghd...
nsIMsgSearchSession
nsmsgsearchtype setsearchparam(in nsmsgsearchtype type, in voidptr param); [noscript] void addresultelement(in nsmsgresultelement element); boolean matchhdr(in nsimsgdbhdr amsghdr, in nsimsgdatabase adatabase); void addsearchhit(in nsimsgdbhdr header, in nsimsgfolder folder); attributes attribute type description searchterms nsisupportsarray readonly: numsearchterms unsigned long readonly: runningadapter nsimsgsearchadapter readonly: searchparam voidptr not scriptable and readonly: searchtype nsmsgsearchtype readonly: numresults long readonly: window nsimsgwindow constants name value description boolean...
nsIPrompt
assword(in wstring dialogtitle, in wstring text, inout wstring password, in wstring checkmsg, inout boolean checkvalue); boolean promptusernameandpassword(in wstring dialogtitle, in wstring text, inout wstring username, inout wstring password, in wstring checkmsg, inout boolean checkvalue); boolean select(in wstring dialogtitle, in wstring text, in pruint32 count, [array, size_is(count)] in wstring selectlist, out long outselection); constants the button flags defined in nsiprompt are the same as those defined in nsipromptservice.constants.
nsIPropertyBag
goodies obtained from window.navigator are: appcodename:"mozilla" appname:"netscape" appversion:"5.0 (windows)" battery:batterymanager buildid:"20140529161749" cookieenabled:true donottrack:"yes" geolocation:geolocation language:"en-us" mimetypes:mimetypearray mozalarms:null mozapps:xpcwrappednative_nohelper mozcameras:cameramanager mozconnection:mozconnection mozcontacts:contactmanager mozid:null mozkeyboard:xpcwrappednative_nohelper mozpay:null mozpermissionsettings:null mozphonenumberservice:phonenumberservice mozpower:mozpowermanager moztcpsocket:null online:true oscpu:"windows nt 5.1" platform:"win32" plugins:pluginarray product:"gecko" productsub...
nsIPushService
message.binary(); // returns a byte array.
nsISHEntry
refreshurilist nsisupportsarray saved refresh uri list for the content viewer.
nsITaskbarPreviewButton
dismissonclick boolean if true, the array of previews should be dismissed when the button is clicked.
nsITraceableChannel
resource://gre/modules/services.jsm'); var binaryinputstream = cc('@mozilla.org/binaryinputstream;1', 'nsibinaryinputstream', 'setinputstream'); var binaryoutputstream = cc('@mozilla.org/binaryoutputstream;1', 'nsibinaryoutputstream', 'setoutputstream'); var storagestream = cc('@mozilla.org/storagestream;1', 'nsistoragestream', 'init'); function tracinglistener() { this.receivedchunks = []; // array for incoming data.
nsITreeColumns
length long an alias for count (for the benefit of scripts which treat this as an array).
XPCOM primitive
the main use case is to store primitive values in a data structure that can only store xpcom objects, such as nsiarray.
XPCOM Interface Reference by grouping
sifeedcontainer nsifeedelementbase nsifeedentry nsifeedgenerator nsifeedperson nsifeedprocessor nsifeedprogresslistener nsifeedresult nsifeedresultlistener nsifeedtextconstruct script mozijssubscriptloader storage mozistoragevacuumparticipant util nsieffectivetldservice worker nsiabstractworker data nsiarray nsicategorymanager nsicollection nsidictionary nsimutablearray nsisimpleenumerator nsisupportschar nsisupportsdouble nsisupportsfloat nsisupportsid nsisupportsinterfacepointer nsisupportsprbool nsisupportsprimitive nsisupportsprint16 nsisupportsprint32 nsisupportsprint64 nsisupportspriority nsisupportsprtime nsisupportspruint...
NS_CStringAppendData
adata [in] a raw character array to copy into this string.
NS_CStringGetMutableData
it returns a pointer to the first element of an array of characters that may be modified in-place.
NS_CStringInsertData
adata [in] a raw character array to copy into this string.
NS_CStringSetData
adata [in] a raw character array to copy into this string.
NS_CStringSetDataRange
adata [in] a raw character array to copy into this string.
NS_StringAppendData
adata [in] a raw character array to copy into this string.
NS_StringInsertData
adata [in] a raw character array to copy into this string.
NS_StringSetData
adata [in] a raw character array to copy into this string.
NS_StringSetDataRange
adata [in] a raw character array to copy into this string.
nsStaticModuleInfo
#include "nsxpcom.h" struct nsstaticmoduleinfo { const char* name; nsgetmoduleproc getmodule; }; members name this member provides the name of the module as a null-terminated, ascii-valued character array.
XPCOM
file and memory management, threads, basic data structures (strings, arrays, variants), etc.
XPIDL Syntax
MozillaTechXPIDLSyntax
the following is a list of potential features which are parseable but may not result in expected code: struct, union, and enumerated types array declarators (appears to be supported in xpidl_header.c but not xpidl_typelib.c) exception declarations module declarations variable arguments (that makes the abnf get more wonky) sequence types max-length strings fixed-point numbers "any" and "long double" types.
Address Book examples
addressbook.modifycard(card); deleting contacts once you have obtained a card(s) from an nsiabdirectory (see above) you can delete one or more simply by calling the deletecards function: let cardstodelete = components.classes["@mozilla.org/array;1"] .createinstance(components.interfaces.nsimutablearray); cardstodelete.appendelement(card); // repeat append as necessary addressbook.deletecards(cardstodelete); how do i add and use my own properties?
DB Views (message lists)
these are the main view classes: nsmsgthreadeddbview - (implementation) nsmsgsearchdbview - (implementation) nsmsgquicksearchdbview - (implementation) nsmsgxfvirtualfolderdbview - (implementation) nsmsggroupview - (implementation) usually, a view object has parallel arrays, which map directly to lines in the message list: m_keys message header key m_flags 32 bits, combination of message header flags and view-only flags (e.g., collapsed) m_level the indentation level when in threaded mode.
Gloda examples
query=gloda.newquery(gloda.noun_conversation); query.subjectmatches("gloda makes searching easy"); query.getcollection(alistener) search messages by tags searches for all messages having any (or several) of all tags defined in tb let query = gloda.newquery(gloda.noun_message); let tagarray = mailservices.tags.getalltags({}); query.tags(...tagarray); let collection = query.getcollection(mylistener); search messages by daterange searches for all messages within a date range id_q=gloda.newquery(gloda.noun_message); // define a date range form yesterday to now id_q.daterange([new date() - 86400000, new date()]); var mylistener = { /* called when new items are returned b...
Creating a Custom Column
from nsitreeview: getcellproperties(row, col, props): optionally modify the props array getrowproperties(row, props): optionally modify the props array getimagesrc(row, col): return a string (or null) getcelltext(row, col): return a string representing the actual text to display in the column from nsimsgcustomcolumnhandler: getsortstringforrow(hdr): return the string value that the column will be sorted by getsortlongforrow(hdr): return the long value that the column will b...
Using JS in Mozilla code
arraybuffer.transfer() proposed for es2016 no, nightly-only for now sharedarraybuffer, sharedint8array..., atomics proposed for es2016 no, nightly-only for now typedobject proposed for es2016 no, nightly-only for now simd proposed for es2016 no, nightly-only for now ...
Using popup notifications
you can use this to style the icon, like this: .popup-notification-icon[popupid="sample-popup"] { list-style-image: url("chrome://popupnotifications/skin/mozlogo.png"); } with this css in place, the result is the look we want: adding secondary options to provide options in the drop-down menu, add an array of notification actions to the call to the show() method, like this: popupnotifications.show(gbrowser.selectedbrowser, "sample-popup", "this is a sample popup notification.", null, /* anchor id */ { label: "do something", accesskey: "d", callback: function() { alert("doing something awesome!"); } }, [ ...
Using COM from js-ctypes
nsigned_short; let wchar = ctypes.jschar; // advanced types - based on simple types let hresult = long; let lpcwstr = wchar.ptr; // guess types - these just work i couldnt find a proper defintion for it let lpunknown = ctypes.voidptr_t; // structures // simple structures let guid = ctypes.structtype('guid', [ { 'data1': ulong }, { 'data2': ushort }, { 'data3': ushort }, { 'data4': byte.array(8) } ]); // advanced structures let clsid = guid; let iid = guid; // super advanced structures let refiid = iid.ptr; let refclsid = clsid.ptr; // vtables let ispvoicevtbl = ctypes.structtype('ispvoicevtbl'); let ispvoice = ctypes.structtype('ispvoice', [{ 'lpvtbl': ispvoicevtbl.ptr }]); ispvoicevtbl.define([ // start inherit from iunknown { 'queryinterface': ctypes.voidptr_t }, ...
Declaring and Using Callbacks
the first argument is the calling convention, the second argument is the return type, and the third is an array of arguments the callback expects.
Standard OS Libraries
undrestanding js-ctypes is important as arrays and other features used in jni.jsm will require us to create arrays from the types available to the ctypes.jsm module.
Library
exceptions thrown ctypes ctype functiontype abi typeerror the return type was specified as an array.
js-ctypes reference
ctypes.arraytype(type, [length]) and the .array() method, which creates a new type describing an array of objects of an existing type.
js-ctypes
using js-ctypes ctypes.open custom native file standard os libraries finding window handles working with data working with arraybuffers declaring types declaring and calling functions declaring and using callbacks type conversion memory management chromeworker js-ctypes reference a reference guide to the js-ctypes api.
Plug-in Basics - Plugins
note that with an object element, param values are also sent in this array after the attributes, separated by a param entry.
DOM Property Viewer - Firefox Developer Tools
up to three properties of an object and items of an array are displayed.
Debugger.Environment - Firefox Developer Tools
names() return an array of strings giving the names of the identifiers bound by this environment.
Debugger.Frame - Firefox Developer Tools
when non-null, this is an object, allocated in the same global as the debugger, with array.prototype on its prototype chain, a non-writable length property, and properties whose names are array indices.
Debugger.Source - Firefox Developer Tools
binary if the instance refers to webassembly code and the debugger has the allowwasmbinarysource property set, a uint8array that contains the webassembly bytecode.
Tutorial: Set a breakpoint - Firefox Developer Tools
if you have more than one tab visiting a file: url, they all share a single content process, so you may need to use a different element of the array as the debuggee.
Index - Firefox Developer Tools
arrays and objects are shown collapsed, and you can expand them using the "+" icons.
JSON viewer - Firefox Developer Tools
arrays and objects are shown collapsed, and you can expand them using the "+" icons.
Network monitor toolbar - Firefox Developer Tools
a set of tool icons: pause (or resume) recording network log search the log request blocking an array of buttons to filter the network request list by type: by the content type of the response xhr requests websocket upgrades and messages (labeled ws) other requests a checkbox that allows you to disable caching.
Call Tree - Firefox Developer Tools
to do this, it generates some arrays filled with random integers and sorts them using each algorithm in turn.
IndexedDB - Firefox Developer Tools
indexes — array of indexes present in the object store as shown below.
Storage Inspector - Firefox Developer Tools
a string containing a key separated value, like "1~2~3~4" or "1=2=3=4" is shown like an array: [1, 2, 3, 4].
Tips - Firefox Developer Tools
$$() returns an array with the results from document.queryselectorall().
AbsoluteOrientationSensor - Web APIs
model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requesting permissions for multiple device sensors.
AddressErrors - Web APIs
if the request's shippingaddress has a value for country which isn't in the array validcountries, we generate the error.
AudioBufferSourceNode.detune - Web APIs
example const audioctx = new audiocontext(); const channelcount = 2; const framecount = audioctx.samplerate * 2.0; // 2 seconds const myarraybuffer = audioctx.createbuffer(channelcount, framecount, audioctx.samplerate); for (let channel = 0; channel < channelcount; channel++) { const nowbuffering = myarraybuffer.getchanneldata(channel); for (let i = 0; i < framecount; i++) { nowbuffering[i] = math.random() * 2 - 1; } } const source = audioctx.createbuffersource(); source.buffer = myarraybuffer; source.connect(audioctx.desti...
AudioBufferSourceNode.loop - Web APIs
you can run the full example live (or view the source.) function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop = true; }, function(e){"error with decoding audio data" + e.e...
AudioBufferSourceNode.loopEnd - Web APIs
function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; songlength = buffer.duration; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop = true; loopstartcontrol.s...
AudioBufferSourceNode.loopStart - Web APIs
function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; songlength = buffer.duration; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop = true; loopstartcontrol.se...
AudioBufferSourceNode.playbackRate - Web APIs
<input class="playback-rate-control" type="range" min="0.25" max="3" step="0.05" value="1"> <span class="playback-rate-value">1.0</span> function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); source.loop = true; }, function(e){"error with decoding audio data" + e.e...
AudioParam.cancelScheduledValues() - Web APIs
examples var gainnode = audioctx.creategain(); gainnode.gain.setvaluecurveattime(wavearray, audioctx.currenttime, 2); //'gain' is the audioparam gainnode.gain.cancelscheduledvalues(audioctx.currenttime); specifications specification status comment web audio apithe definition of 'cancelscheduledvalues' in that specification.
AudioParam - Web APIs
audioparam.setvaluecurveattime() schedules the values of the audioparam to follow a set of values, defined by an array of floating-point numbers scaled to fit into the given interval, starting at a given start time and spanning a given duration of time.
AudioProcessingEvent - Web APIs
octx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { ...
AudioTrack.enabled - Web APIs
the element's audio tracks are then scanned through using the javascript foreach() method (although the audiotracks property of a media element isn't actually a javascript array, it can be accessed like one for the most part).
AudioTrackList.length - Web APIs
each track can be accessed by treating the audiotracklist as an array of objects of type audiotrack.
AudioTrackList - Web APIs
the individual tracks can be accessed using array syntax.
AudioWorkletGlobalScope.registerProcessor - Web APIs
typeerror the processorctor is not a callable constructor, or the parameterdescriptors property of the constructor exists and doesn't return an array of audioparamdescriptor-based objects.
AudioWorkletGlobalScope - Web APIs
ly output silence, // which the outputs are already filled with process (inputs, outputs, parameters) { return true } } // the sample rate is not going to change ever, // because it's a read-only property of a baseaudiocontext // and is set only during its instantiation console.log(samplerate) // you can declare any variables and use them in your processors // for example it may be an arraybuffer with a wavetable const usefulvariable = 42 console.log(usefulvariable) registerprocessor('test-processor', testprocessor) next, in our main scripts file we'll load the processor, create an instance of audioworkletnode — passing the name of the processor to it — and connect the node to an audio graph.
AudioWorkletNode.parameters - Web APIs
parameters['customgain'][i] : parameters['customgain'][0]) // note: a parameter contains an array of 128 values (one value for each of 128 samples), // however it may contain a single value which is to be used for all 128 samples // if no automation is scheduled for the moment.
AudioWorkletNode - Web APIs
if the audioworkletprocessor has a static parameterdescriptors getter, the audioparamdescriptor array returned from it is used to create audioparam objects on the audioworkletnode.
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
parameters['customgain'][i] : parameters['customgain'][0]) // note: a parameter contains an array of 128 values (one value for each of 128 samples), // however it may contain a single value which is to be used for all 128 samples // if no automation is scheduled for the moment.
BaseAudioContext.createConvolver() - Web APIs
// grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg', true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ...
BaseAudioContext.createScriptProcessor() - Web APIs
octx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { ...
BaseAudioContext.createWaveShaper() - Web APIs
amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } return curve; }; ...
Using the Beacon API - Web APIs
the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata.
BeforeInstallPromptEvent - Web APIs
beforeinstallpromptevent.platforms read only returns an array of domstring items containing the platforms on which the event was dispatched.
BiquadFilterNode - Web APIs
biquadfilternode.getfrequencyresponse() from the current filter parameter settings this method calculates the frequency response for frequencies specified in the provided array of frequencies.
Blob.stream() - Web APIs
WebAPIBlobstream
this returns an array containing two new readablestream objects, each of which returns the contents of the blob.
Bluetooth.getDevices() - Web APIs
return value a promise that resolves with an array of bluetoothdevices.
Bluetooth - Web APIs
WebAPIBluetooth
bluetooth.getdevices() returns a promise that resolved to an array of bluetoothdevices which the origin already obtained permission for via a call to bluetooth.requestdevice().
manufacturerData - Web APIs
the manufacturerdata read-only property of the bluetoothadvertisingdata interface returns a map that relates company identifier codes to arraybuffers.
serviceData - Web APIs
the servicedata read-only property of the bluetoothadvertisingdata interface returns a map that relates uuids to arraybuffers.
BluetoothDevice.uuids - Web APIs
syntax var uuids[] =​ instanceofbluetoothdevice.uuids returns an array.
BluetoothDevice - Web APIs
gatt; readonly attribute frozenarray uuids; promise watchadvertisements(); void unwatchadvertisements(); readonly attribute boolean watchingadvertisements; }; bluetoothdevice implements eventtarget; bluetoothdevice implements bluetoothdeviceeventhandlers; bluetoothdevice implements characteristiceventhandlers; bluetoothdevice implements serviceeventhandlers; properties bluetoothdevice.id read only a domstring that uni...
getCharacteristics() - Web APIs
} ) returns a promise to an array of bluetoothgattcharacteristic instances.
getIncludedServices() - Web APIs
the bluetoothgattservice.getincludedservices() method returns a promise to an array of bluetoothgattservice instances for an optional universally unique identifier (uuid).
Body.json() - Web APIs
WebAPIBodyjson
this object could be anything that can be represented by json — an object, an array, a string, a number...
Body.text() - Web APIs
WebAPIBodytext
example in our fetch text example (run fetch text live), we have an <article> element and three links (stored in the mylinks array.) first, we loop through all of these and give each one an onclick event handler so that the getdata() function is run — with the link's data-page identifier passed to it as an argument — when one of the links is clicked.
BudgetService.getBudget() - Web APIs
the getbudget() property of the budgetservice interface returns a promise that resolves to an array of budgetstate objects indicating the expected state of the budget at times in the future.
BudgetService - Web APIs
budgetservice.getbudget() returns a promise that resolves to an array of budgetstate objects, indicating the expected state of the budget at times in the future.
BufferSource - Web APIs
buffersource is a typedef used to represent objects that are either themselves an arraybuffer, or which are a typedarray providing an arraybufferview.
CSSMathProduct - Web APIs
properties cssmathproduct.values returns a cssnumericarray object which contains one or more cssnumericvalue objects.
CSSMathValue.operator - Web APIs
<div>my width has a <code>calc()</code> function</div> we assign a width with a calculation div { width: calc(50% - 0.5vw); } we add the javascript const stylemap = document.queryselector('div').computedstylemap(); console.log( stylemap.get('width') ); // cssmathsum {values: cssnumericarray, operator: "sum"} console.log( stylemap.get('width').values ); // cssnumericarray {0: cssunitvalue, 1: cssmathnegate, length: 2} console.log( stylemap.get('width').operator ); // 'sum' console.log( stylemap.get('width').values[1].operator ) // 'negate' the cssmathvalue.operator returns sum for the equation and negate for the operator on the second value.
CSSMathValue - Web APIs
<div>has width</div> we assign a width with a calculation div { width: calc(30% - 20px); } we add the javascript const stylemap = document.queryselector('div').computedstylemap(); console.log( stylemap.get('width') ); // cssmathsum {values: cssnumericarray, operator: "sum"} console.log( stylemap.get('width').operator ); // 'sum' console.log( stylemap.get('width').values[1].value ); // -20 the cssmathvalue.operator returns 'sum' because stylemap.get('width').values[1].value ); is -20: adding a negative number.
CSSNumericValue - Web APIs
cssmathinvert cssmathmax cssmathmin cssmathnegate cssmathproduct cssmathsum cssmathvalue cssnumericarray cssperspective csspositionvalue cssrotate cssskew cssskeyx cssskeyw csstranslate cssunitvalue properties none.
CSSRuleList - Web APIs
a cssrulelist is an (indirect-modify only) array-like object containing an ordered collection of cssrule objects.
CSSStyleDeclaration.setProperty() - Web APIs
we then loop through the different rules contained inside the stylesheet, which are contained in the array found at stylesheet.cssrules; for each one, we check whether its cssstylerule.selectortext property is equal to the selector .box p, which indicates it is the one we want.
CSSStyleSheet.cssRules - Web APIs
examples individual rules within the stylesheet can then be accessed by index: let rulelist = document.stylesheets[0].cssrules; for (let i=0; i < rulelist.length; i++) { processrule(rulelist[i]); } rules can also be accessed using for...of: let rulelist = document.stylesheets[0].cssrules; for (let rule of rulelist) { processrule(rule); } however, because cssrule is not a proper array, you can't use foreach().
CSSStyleValue - Web APIs
cssstylevalue.parseall() sets all occurences of a specific css property to the specified valueand returns an array of cssstylevalue objects, each containing one of the supplied values.
CSSUnparsedValue.CSSUnparsedValue() - Web APIs
syntax var cssunparsedvalue = new cssunparsedvalue(members) parameters members an array whose values must be either a usvstring or a cssvariablereferencevalue.
CSS Object Model (CSSOM) - Web APIs
css typed object model cssimagevalue csskeywordvalue cssmathinvert cssmathmax cssmathmin cssmathnegate cssmathproduct cssmathsum cssmathvalue cssmatrixcomponent cssnumericarray cssnumericvalue cssperspective csspositionvalue cssrotate cssscale cssskew cssskewx cssskewy cssstylevalue csstransformcomponent csstransformvalue csstranslate cssunitvalue cssunparsedvalue cssvariablereferencevalue stylepropertymap stylepropertymapreadonly obsolete cssom interfaces cssprimitivevalue cssvalue cssvaluelist ...
Cache.match() - Web APIs
WebAPICachematch
note: cache.match() is basically identical to cache.matchall(), except that rather than resolving with an array of all matching responses, it resolves with the first matching response only (that is, response[0]).
CanvasRenderingContext2D.getTransform() - Web APIs
the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] note: the returned object is not live, so updating it will not affect the current transformation matrix, and updating the current transformation matrix will not affect an already returned dommatrix.
CanvasRenderingContext2D.setTransform() - Web APIs
syntax ctx.settransform(a, b, c, d, e, f); ctx.settransform(matrix); the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] parameters settransform() has two types of parameter that it can accept.
CanvasRenderingContext2D.transform() - Web APIs
syntax void ctx.transform(a, b, c, d, e, f); the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] parameters a (m11) horizontal scaling.
A basic ray-caster - Web APIs
the code does attempt to be very efficient, using array look-ups of pre-computed values, but i'm no optimization guru, so things could probably be written faster.
Transformations - Web APIs
the transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] if any of the arguments are infinity the transformation matrix must be marked as infinite instead of the method throwing an exception.
Channel Messaging API - Web APIs
portcollection an array of messageports; an experimental solution to allow broadcasting of a message to multiple ports simultaneously.
ChildNode.after() - Web APIs
WebAPIChildNodeafter
higher with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/after()/after().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('after')) { return; } object.defineproperty(item, 'after', { configurable: true, enumerable: true, writable: true, value: function after() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ?
ChildNode.before() - Web APIs
WebAPIChildNodebefore
er with the following code: // from: https://github.com/jserz/js_piece/blob/master/dom/childnode/before()/before().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('before')) { return; } object.defineproperty(item, 'before', { configurable: true, enumerable: true, writable: true, value: function before() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ?
Clients.matchAll() - Web APIs
WebAPIClientsmatchAll
return value a promise that resolves to an array of client objects.
Clients - Web APIs
WebAPIClients
clients.matchall() returns a promise for an array of client objects.
Clipboard.write() - Web APIs
WebAPIClipboardwrite
syntax var promise = navigator.clipboard.write(data) parameters data an array of clipboarditem objects containing data to be written to the clipboard.
ClipboardItem.types - Web APIs
the read-only types property of the clipboarditem interface returns an array of mime types available within the clipboarditem syntax var types = clipboarditem.types; value an array of available mime types.
ClipboardItem - Web APIs
types read only returns an array of mime types available within the clipboarditem.
ContentIndex.add() - Web APIs
WebAPIContentIndexadd
homepage article video audio icons: optional an array of image resources, defined as an object with the following data: src: a url string of the source image.
ContentIndex - Web APIs
async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const listelem = document.createelement('ul'); for (const entry of entri...
Content Index API - Web APIs
async function createreadinglist() { // access our service worker registration const registration = await navigator.serviceworker.ready; // get our index entries const entries = await registration.index.getall(); // create a containing element const readinglistelem = document.createelement('div'); // test for entries if (!array.length) { // if there are no entries, display a message const message = document.createelement('p'); message.innertext = 'you currently have no articles saved for offline reading.' readinglistelem.append(message); } else { // if entries are present, display in a list of links to the content const listelem = document.createelement('ul'); for (const entry of entri...
ConvolverNode.buffer - Web APIs
// grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg', true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ...
ConvolverNode.normalize - Web APIs
// grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg', true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ...
ConvolverNode - Web APIs
let audioctx = new window.audiocontext(); async function createreverb() { let convolver = audioctx.createconvolver(); // load impulse response from file let response = await fetch("path/to/impulse-response.wav"); let arraybuffer = await response.arraybuffer(); convolver.buffer = await audioctx.decodeaudiodata(arraybuffer); return convolver; } ...
Crypto - Web APIs
WebAPICrypto
crypto.getrandomvalues() fills the passed typedarray with cryptographically sound random values.
CustomEvent - Web APIs
event.deeppath an array of dom nodes through which the event has bubbled.
DOMMatrix() - Web APIs
syntax var dommatrix = new dommatrix([init]) parameters init optional a string containing a sequence of numbers or an array of numbers specifying the matrix you want to create, or a css transform string.
DOMMatrixReadOnly() - Web APIs
syntax var dommatrixreadonly = new dommatrixreadonly([init]) parameters init optional either a string containing a sequence of numbers or an array of integers specifying the matrix you want to create.
DOMTokenList - Web APIs
it is indexed beginning with 0 as with javascript array objects.
DataTransfer - Web APIs
datatransfer.types read only an array of strings giving the formats that were set in the dragstart event.
DataTransferItem.webkitGetAsEntry() - Web APIs
note that to read all files in a directory, readentries needs to be called repeatedly until it returns an empty array.
DataTransferItemList.DataTransferItem() - Web APIs
the datatransferitem() getter method implements support for accessing items in the datatransferitemlist using array-style syntax (that is datatransferitem[index]).
DeprecationReportBody - Web APIs
t innerlist = document.createelement('ul'); listitem.appendchild(innerlist); list.appendchild(listitem); for (let key in reports[i].body) { let innerlistitem = document.createelement('li'); let keyvalue = reports[i].body[key]; innerlistitem.textcontent = key + ': ' + keyvalue; innerlist.appendchild(innerlistitem); } } } the reports parameter contains an array of all the reports in the observer's report queue.
DirectoryReaderSync - Web APIs
call this method until an empty array is returned.
DisplayMediaStreamConstraints.video - Web APIs
the value may be a single one of the following strings, or an array of them to allow the browser flexibility in deciding what to do about the cursor.
Document.all - Web APIs
WebAPIDocumentall
in other words, it returns all of the document's elements, accessible by order (like an array) and by id (like a regular object).
Document.createTouchList() - Web APIs
note: firefox also accepts an array of touch objects.
Document.createTreeWalker() - Web APIs
example the following example goes through all nodes in the body, reduces the set of nodes to elements, simply passes through as acceptable each node (it could reduce the set in the acceptnode() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array.
Document.images - Web APIs
WebAPIDocumentimages
usage notes you can use either javascript array notation or the item() method on the returned collection to access the items in the collection.
Document.plugins - Web APIs
WebAPIDocumentplugins
syntax embedarrayobj = document.plugins value an htmlcollection, or null if there are no embeds in the document.
Document.scripts - Web APIs
WebAPIDocumentscripts
you can use this just like an array to get all the elements in the list.
DocumentTimeline.DocumentTimeline() - Web APIs
this bit of code would start all the cats animating 500 milliseconds into their animations: var cats = document.queryselectorall('.sharedtimelinecat'); cats = array.prototype.slice.call(cats); var sharedtimeline = new documenttimeline({ origintime: 500 }); cats.foreach(function(cat) { var catkeyframes = new keyframeeffect(cat, keyframes, timing); var catanimation = new animation(catkeyframes, sharedtimeline); catanimation.play(); }); specifications specification status comment web animationsthe definition of 'documenttimeli...
Examples of web and XML development using the DOM - Web APIs
example 1: height and width the following example shows the use of the height and width properties alongside images of varying dimensions: <!doctype html> <html lang="en"> <head> <title>width/height example</title> <script> function init() { var arrimages = new array(3); arrimages[0] = document.getelementbyid("image1"); arrimages[1] = document.getelementbyid("image2"); arrimages[2] = document.getelementbyid("image3"); var objoutput = document.getelementbyid("output"); var strhtml = "<ul>"; for (var i = 0; i < arrimages.length; i++) { strhtml += "<li>image" + (i+1) + ": height=" + arrimages[i].height + ", width=" + ar...
EffectTiming.fill - Web APIs
WebAPIEffectTimingfill
var boxrotationkeyframes = [ { transform: "rotate(-90deg)" }, { transform: "rotate(90deg)" } ]; the boxrotationkeyframes object is an array of keyframes, each describing the state of the affected element at a point in the animation process.
Element.attributes - Web APIs
it is a namednodemap, not an array, so it has no array methods and the attr nodes' indexes may differ among browsers.
Element.shadowRoot - Web APIs
from here we use standard dom traversal techniques to find the <style> element inside the shadow dom and then update the css found inside it: function updatestyle(elem) { const shadow = elem.shadowroot; const childnodes = array.from(shadow.childnodes); childnodes.foreach(childnode => { if (childnode.nodename === 'style') { childnode.textcontent = ` div { width: ${elem.getattribute('l')}px; height: ${elem.getattribute('l')}px; background-color: ${elem.getattribute('c')}; } `; } }); } specifications specification status comment ...
Encoding API - Web APIs
stringview – a c-like representation of strings based on typed arrays.
Event.composed - Web APIs
WebAPIEventcomposed
the <open-shadow> element's composed path is this: array [ p, shadowroot, open-shadow, body, html, htmldocument https://mdn.github.io/web-components-examples/composed-composed-path/, window ] whereas the <closed-shadow> element's composed path is a follows: array [ closed-shadow, body, html, htmldocument https://mdn.github.io/web-components-examples/composed-composed-path/, window ] in the second case, the event listeners only propagate as far as th...
Event - Web APIs
WebAPIEvent
event.deeppath an array of dom nodes through which the event has bubbled.
ExtendableMessageEvent() - Web APIs
ports: an array containing the messageport objects connected to the channel sending the message.
ExtendableMessageEvent.ports - Web APIs
the ports read-only property of the extendablemessageevent interface returns the array containing the messageport objects representing the ports of the associated message channel (the channel the message is being sent through.) syntax var myports = extendablemessageevent.ports; value an array of messageport objects.
ExtendableMessageEvent - Web APIs
extendablemessageevent.ports read only returns the array containing the messageport objects representing the ports of the associated message channel.
FeaturePolicy.allowedFeatures() - Web APIs
return value an array of strings representing the feature policy directive names that are allowed by the feature policy this method is called on.
FeaturePolicy.getAllowlistForFeature() - Web APIs
however, it will also return empty array, inditating that no origin is allowed to use the feature.
File.File() - Web APIs
WebAPIFileFile
syntax new file(bits, name[, options]); parameters bits an array of arraybuffer, arraybufferview, blob, usvstring objects, or a mix of any of such objects, that will be put inside the file.
File.getAsBinary() - Web APIs
WebAPIFilegetAsBinary
note: this method is obsolete; you should use the filereader method readasbinarystring() or readasarraybuffer() instead.
File.getAsDataURL() - Web APIs
WebAPIFilegetAsDataURL
syntax var url = instanceoffile.getasdataurl(); returns a string representing a data: url example // fileinput is a htmlinputelement: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; // array with acceptable file types var accept = ["image/png"]; // img is a htmlimgelement: <img id="myimg"> var img = document.getelementbyid("myimg"); // if we accept the first selected file type if (accept.indexof(files[0].mediatype) > -1) { // display the image // same as <img src="data:image/png,<imagedata>"> img.src = files[0].getasdataurl(); } specification not part of any specification.
FileReader.onload - Web APIs
WebAPIFileReaderonload
the filereader.onload property contains an event handler executed when the load event is fired, when content read with readasarraybuffer, readasbinarystring, readasdataurl or readastext is available.
FileReader.readAsBinaryString() - Web APIs
using filereader.readasarraybuffer() is recommended.
FileReader - Web APIs
filereader.readasarraybuffer() starts reading the contents of the specified blob, once finished, the result attribute contains an arraybuffer representing the file's data.
FileReaderSync.readAsBinaryString() - Web APIs
note: this method is deprecated in favor of readasarraybuffer().
File and Directory Entries API support in Firefox - Web APIs
there are only two ways to get access to file system entries at this time: the <input> element, using the htmlinputelement.webkitentries property to access an array of filesystementry objects describing file system entries you can then read.
FontFace - Web APIs
WebAPIFontFace
constructor fontface() constructs and returns a new fontface object, built from an external resource described by an url or from an arraybuffer.
FontFaceSet.load() - Web APIs
WebAPIFontFaceSetload
syntax result = afontfaceset.load(font); result = afontfaceset.load(font, text); returns a promise of an array of fontface loaded.
FontFaceSetLoadEvent.FontFaceSetLoadEvent() - Web APIs
options optional options are as follows: fontfaces: an array of fontface instances.
FontFaceSetLoadEvent - Web APIs
properties fontfacesetloadevent.fontfacesread only returns an array of fontface instances each of which represents a single usable font.
FormData - Web APIs
WebAPIFormData
formdata.getall() returns an array of all the values associated with a given key from within a formdata.
FormDataEntryValue - Web APIs
the formdata.get() method returns a single value while formdata.getall() returns an array of formdataentryvalues.
Gamepad API - Web APIs
extensions to other interfaces navigator navigator.getgamepads() an extension to the navigator object that returns an array of gamepad objects, one for each connected gamepad.
HTMLCollection.item - Web APIs
in javascript, it is easier to treat the htmlcollection as an array and to index it using array notation.
HTMLFormControlsCollection.namedItem() - Web APIs
like that one, in javascript, using the array bracket syntax with a string, like collection["value"] is equivalent to collection.nameditem("value").
HTMLFormControlsCollection - Web APIs
like that one, in javascript, using the array bracket syntax with a string, like collection["value"] is equivalent to collection.nameditem("value").
HTMLMediaElement.audioTracks - Web APIs
the list of tracks can be accessed using array notation, or using the object's gettrackbyid() method.
HTMLMediaElement.seekable - Web APIs
examples var video = document.queryselector("video"); var timerangesobject = video.seekable; var timeranges = []; //go through the object and output an array for (let count = 0; count < timerangesobject.length; count ++) { timeranges.push([timerangesobject.start(count), timerangesobject.end(count)]); } specifications specification status comment html living standardthe definition of 'htmlmediaelement' in that specification.
HTMLMedia​Element​.textTracks - Web APIs
the list of tracks can be accessed using array notation, or using the object's gettrackbyid() method.
HTMLMediaElement.videoTracks - Web APIs
the list of tracks can be accessed using array notation, or using the object's gettrackbyid() method.
HTMLSelectElement.item() - Web APIs
in javascript, using the array bracket syntax with an unsigned long, like selectelt[index] is equivalent to selectelt.nameditem(index).
HTMLSelectElement.namedItem() - Web APIs
in javascript, using the array bracket syntax with a string, like selectelt["value"] is equivalent to selectelt.nameditem("value").
HTMLSlotElement.assignedElements() - Web APIs
return value an array of elements.
HTMLSlotElement.assignedNodes() - Web APIs
return value an array of nodes.
HTMLTableElement.rows - Web APIs
example myrows = mytable.rows; firstrow = mytable.rows[0]; lastrow = mytable.rows.item(mytable.rows.length-1); this demonstrates how you can use both array syntax (line 2) and the htmlcollection.item() method (line 3) to obtain individual rows in the table.
HTMLTrackElement: cuechange event - Web APIs
bubbles no cancelable no interface event event handler oncuechange examples on the texttrack you can set up a listener for the cuechange event on a texttrack using the addeventlistener() method: track.addeventlistener('cuechange', function () { let cues = track.activecues; // array of current cues }); or you can just set the oncuechange event handler property: track.oncuechange = function () { let cues = track.activecues; // array of current cues } on the track element the underlying texttrack, indicated by the track property, receives a cuechange event every time the currently-presented cue is changed.
Drag Operations - Web APIs
the types property returns an array of the string types that were added when the drag began, in the order from most significant to least significant.
Dragging and Dropping Multiple Items - Web APIs
the following example retrieves a set of files being dragged and adds them to an array.
Recommended Drag Types - Web APIs
updates to datatransfer.types the latest spec dictates that datatransfer.types should return a frozen array of domstrings rather than a domstringlist (this is supported in firefox 52 and above).
IDBFactory.cmp() - Web APIs
WebAPIIDBFactorycmp
note: do not use this method for comparing arbitrary javascript values, because many javascript values are either not valid indexeddb keys (booleans and objects, for example) or are treated as equivalent indexeddb keys (for example, since indexeddb ignores arrays with non-numeric properties and treats them as empty arrays, so any non-numeric arrays are treated as equivalent).
IDBIndex.getAll() - Web APIs
WebAPIIDBIndexgetAll
if you are trying to get an array of all the objects in an object store, though, you should use getall().
IIRFilterNode - Web APIs
it also has the following additional methods: getfrequencyresponse() uses the filter's current parameter settings to calculate the response for frequencies specified in the provided array of frequencies.
InputEvent() - Web APIs
ranges: (optional) an array of static ranges that will be affected by a change to the dom if the input event is not canceled.
InputEvent - Web APIs
inputevent.gettargetranges() returns an array of static ranges that will be affected by a change to the dom if the input event is not canceled.
install - Web APIs
method of installtrigger object syntax int install(array xpilist [, function callbackfunc ] ) parameters the install method has the following parameters: xpilist an array of files to be installed (see example below).
IntersectionObserver.observe() - Web APIs
when the visibility of the specified element crosses over one of the observer's visibility thresholds (as listed in intersectionobserver.thresholds), the observer's callback is executed with an array of intersectionobserverentry objects representing the intersection changes which occurred.
IntersectionObserver - Web APIs
intersectionobserver.takerecords() returns an array of intersectionobserverentry objects for all observed targets.
Keyboard.lock() - Web APIs
WebAPIKeyboardlock
syntax var promise = keyboard.lock([keycodes[]]) parameters keycodes optional an array of one or more key codes to lock.
Key Values - Web APIs
media controller keys because modern remote controls for media devices often include buttons beyond the basic controls covered elsewhere in this document, key values are defined for a broad array of these additional buttons.
KeyboardLayoutMap.keys - Web APIs
the keys read-only property of the keyboardlayoutmap interface returns a new array iterator object that contains the keys for each index in the array.
KeyboardLayoutMap.values - Web APIs
the values read-only property of the keyboardlayoutmap interface returns a new array iterator object that contains the values for each index in the map.
LayoutShift - Web APIs
layoutshift.sources returns an array of layoutshiftattribution objects with information on the elements that were shifted.
LockedFile.append() - Web APIs
WebAPILockedFileappend
it can be a string or an arraybuffer.
LockedFile.write() - Web APIs
WebAPILockedFilewrite
it can be a string or an arraybuffer.
LockedFile - Web APIs
lockedfile.readasarraybuffer() allows to retrieve a part of the content of the file as an arraybuffer.
MSRangeCollection - Web APIs
the msrangecollection object is an array of one or more range objects.
MediaDeviceInfo.groupId - Web APIs
the function starts by initializing the result array, devlist, to be an empty array.
MediaDeviceInfo - Web APIs
the list of devices obtained by calling navigator.mediadevices.enumeratedevices() is an array of mediadeviceinfo objects, one per media device.
MediaDevices.getUserMedia() - Web APIs
privacy and security as an api that may involve significant privacy concerns, getusermedia()'s specification lays out a wide array of privacy and security requirements that browsers are obligated to meet.
MediaDevices - Web APIs
enumeratedevices() obtains an array of information about the media input and output devices available on the system.
MediaKeyMessageEvent() - Web APIs
message: an array containing the message generated by the content decryption module.
message - Web APIs
the mediakeymessageevent.message read-only property returns an arraybuffer with a message from the content decryption module.
MediaKeyMessageEvent - Web APIs
mediakeymessageevent.message read only returns an arraybuffer with a message from the content decryption module.
MediaKeyStatusMap.entries() - Web APIs
the entries() read-only property of the mediakeystatusmap interface returns a new iterator object, containing an array of [key, value] pairs for each element in the status map, in insertion order.
audioCapabilities - Web APIs
the mediakeysystemconfiguration.audiocapabilities read-only property returns an array of supported audio type and capability pairs.
videoCapabilities - Web APIs
the mediakeysystemconfiguration.videocapabilities read-only property returns an array of supported video type and capability pairs.
MediaMetadata.MediaMetadata() - Web APIs
artwork: an array of images associated with the playing media.
MediaMetadata - Web APIs
mediametadata.artwork returns or sets an array of images associated with playing media.
MediaRecorderErrorEvent.error - Web APIs
example this function creates and returns a mediarecorder for a given mediastream, configured to buffer data into an array and to watch for errors.
MediaSession.setPositionState() - Web APIs
exceptions typeerror this error can occur in an array of circumstances: the specified mediapositionstate object's duration is missing, negative, or null.
MediaSource - Web APIs
(mimecodec); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; function fetchab (url, cb) { console.log(url); var xhr = new xmlhttprequest; xhr.open('get', url); xhr.responsetype = 'arraybuffer'; xhr.onload = function () { cb(xhr.response); }; xhr.send(); }; specifications specification status comment media source extensionsthe definition of 'mediasource' in that specification.
MediaStream() - Web APIs
tracks an array of mediastreamtrack objects, one for each track to add to the stream.
MediaStream.getTracks() - Web APIs
return value an array of mediastreamtrack objects.
MediaStream - Web APIs
you can create an empty stream, a stream which is based upon an existing stream, or a stream that contains a specified list of tracks (specified as an array of mediastreamtrack objects).
MediaStreamTrack.applyConstraints() - Web APIs
the object may contain an advanced property containing an array of additional mediatrackconstrants objects, which are treated as exact requires.
MediaStreamTrack.muted - Web APIs
example this example counts the number of tracks in an array of mediastreamtrack objects which are currently muted.
Media Source API - Web APIs
we can't, for example, combine/split arraybuffers.
Capabilities, constraints, and settings - Web APIs
advanced constraints so-called advanced constraints are created by adding an advanced property to the constraint set; this property's value is an array of additional constraint sets which are considered optional.
MessageEvent - Web APIs
messageevent.ports read only an array of messageport objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g.
MessagePort.postMessage() - Web APIs
multiple data items can be sent as an array.
MimeType - Web APIs
WebAPIMimeType
navigatorplugins.mimetypes returns an array of this object.
MutationObserver.MutationObserver() - Web APIs
the callback function takes as input two parameters: an array of mutationrecord objects, describing each change that occurred; and the mutationobserver which invoked the callback.
MutationObserver.takeRecords() - Web APIs
return value an array mutationrecord objects, each describing one change applied to the observed portion of the document's dom tree.
MutationObserver - Web APIs
takerecords() removes all pending notifications from the mutationobserver's notification queue and returns them in a new array of mutationrecord objects.
MutationObserverInit - Web APIs
attributefilter optional an array of specific attribute names to be monitored.
NamedNodeMap - Web APIs
objects inside a namednodemap are not in any particular order, unlike nodelist, although they may be accessed by an index as in an array.
Navigator.sendBeacon() - Web APIs
data a arraybuffer, arraybufferview, blob, domstring, formdata, or urlsearchparams object containing the data to send.
navigator.hardwareConcurrency - Web APIs
examples in this example, one worker is created for each logical processor reported by the browser and a record is created which includes a reference to the new worker as well as a boolean value indicating whether or not we're using that worker yet; these objects are, in turn, stored into an array for later use.
NavigatorLanguage - Web APIs
navigatorlanguage.languages read only returns an array of domstring representing the languages known to the user, by order of preference.
NodeList.entries() - Web APIs
WebAPINodeListentries
example var node = document.createelement("div"); var kid1 = document.createelement("p"); var kid2 = document.createtextnode("hey"); var kid3 = document.createelement("span"); node.appendchild(kid1); node.appendchild(kid2); node.appendchild(kid3); var list = node.childnodes; // using for..of for(var entry of list.entries()) { console.log(entry); } results in: array [ 0, <p> ] array [ 1, #text "hey" ] array [ 2, <span> ] ...
NodeList.prototype.forEach() - Web APIs
WebAPINodeListforEach
to all browsers supporting es5: if (window.nodelist && !nodelist.prototype.foreach) { nodelist.prototype.foreach = function (callback, thisarg) { thisarg = thisarg || window; for (var i = 0; i < this.length; i++) { callback.call(thisarg, this[i], i, this); } }; } or if (window.nodelist && !nodelist.prototype.foreach) { nodelist.prototype.foreach = array.prototype.foreach; } the above behavior is how many browsers actually implement nodelist.prototype.foreach() (chrome, for example).
NodeList.item() - Web APIs
WebAPINodeListitem
alternate syntax javascript also offers an array-like bracketed syntax for obtaining an item from a nodelist by index: nodeitem = nodelist[index] example var tables = document.getelementsbytagname("table"); var firsttable = tables.item(1); // or simply tables[1] - returns the second table in the dom specifications specification status comment domthe definition of 'nodelist: item' in that specification.
Notification.Notification() - Web APIs
actions: an array of notificationactions representing the actions available to the user when the notification is presented.
Notification.actions - Web APIs
syntax var actions[] = notification.actions; value a read-only array of notificationaction objects, each describing a single action the user can choose within a notification.
Notification.maxActions - Web APIs
effectively, this is the maximum number of elements in notification.actions array which will be respected by the user agent.
Notification - Web APIs
notification.actions read only the actions array of the notification as specified in the constructor's options parameter.
NotificationEvent.action - Web APIs
the notification id is set during the creation of the notification via the actions array attribute and can't be modified unless the notification is replaced.
NotifyAudioAvailableEvent - Web APIs
properties framebuffer read only a float32array containing the raw 32-bit floating-point audio data obtained from decoding the audio (e.g., the raw data being sent to the audio hardware vs.
OES_texture_float - Web APIs
the pixels parameter now accepts an arraybufferview of type float32array.
OfflineAudioContext.startRendering() - Web APIs
and offline audio context var audioctx = new audiocontext(); var offlinectx = new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.connect(offlinectx.destination); source.start(); //source.loop = true; offlinectx.startrendering().then(function(renderedbuffer) { console.log('rendering completed ...
OfflineAudioContext - Web APIs
and offline audio context var audioctx = new audiocontext(); var offlinectx = new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.connect(offlinectx.destination); source.start(); //source.loop = true; offlinectx.startrendering().then(function(renderedbuffer) { console.log('rendering completed ...
OscillatorNode.setPeriodicWave() - Web APIs
var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag); osc.setperiodicwave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); this works because a sound that contains only a fundamental tone is by definition a sine wave.
ParentNode.append() - Web APIs
WebAPIParentNodeappend
with the following code: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/append()/append().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('append')) { return; } object.defineproperty(item, 'append', { configurable: true, enumerable: true, writable: true, value: function append() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ?
ParentNode.lastElementChild - Web APIs
// returns array instead of htmlcollection.
ParentNode.prepend() - Web APIs
it's not available: // source: https://github.com/jserz/js_piece/blob/master/dom/parentnode/prepend()/prepend().md (function (arr) { arr.foreach(function (item) { if (item.hasownproperty('prepend')) { return; } object.defineproperty(item, 'prepend', { configurable: true, enumerable: true, writable: true, value: function prepend() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ?
PaymentAddress - Web APIs
properties paymentaddress.addressline read only an array of domstring objects providing each line of the address not included among the other properties.
PaymentRequest.onshippingoptionchange - Web APIs
ingoption.amount.value = '0.00'; details.total.amount.value = '55.00'; // shipping to jp is supported } else if (addr.country === 'jp') { shippingoption.id = 'jp'; shippingoption.label = 'international shipping'; shippingoption.amount.value = '10.00'; details.total.amount.value = '65.00'; // shipping to elsewhere is unsupported } else { // empty array indicates rejection of the address details.shippingoptions = []; return promise.resolve(details); console.log(details.error); } // hardcode for simplicity if (details.displayitems.length === 2) { details.displayitems[2] = shippingoption; } else { details.displayitems.push(shippingoption); } details.shippingoptions = [shippingoption]; retu...
performance.getEntries() - Web APIs
syntax general syntax: entries = window.performance.getentries(); return value entries an array of performanceentry objects.
PerformanceResourceTiming.serverTiming - Web APIs
the servertiming read-only property returns an array of performanceservertiming entries containing server timing metrics.
PerformanceResourceTiming - Web APIs
performanceresourcetiming.servertimingread only an array of performanceservertiming entries containing server timing metrics.
PeriodicWave - Web APIs
var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag, {disablenormalization: true}); osc.setperiodicwave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); this works because a sound that contains only a fundamental tone is by definition a s...
PhotoCapabilities.fillLightMode - Web APIs
syntax const lightmodes = photocapabilities.filllightmode value an array of available fill light modes.
PhotoCapabilities - Web APIs
photocapabilities.filllightmode read only returns an array of available fill light options.
Pinch zoom gestures - Web APIs
// global vars to cache event state var evcache = new array(); var prevdiff = -1; register event handlers event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup.
PublicKeyCredential.id - Web APIs
examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (...
PublicKeyCredential.response - Web APIs
examples var options = { challenge: new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey: options }) .then(function (pubkeycredential) { va...
PublicKeyCredentialCreationOptions.attestation - Web APIs
examples var publickey = { attestation: "indirect", challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (...
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
examples var publickey = { authenticatorselection:{ authenticatorattachment: "cross-platform", requireresidentkey: true, userverification: "required" }, challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentiali...
PublicKeyCredentialCreationOptions.challenge - Web APIs
examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (...
PublicKeyCredentialCreationOptions.rp - Web APIs
examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com", icon: "https://login.example.com/login.ico" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { ...
PublicKeyCredentialCreationOptions.timeout - Web APIs
challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (...
PublicKeyCredentialCreationOptions.user - Web APIs
examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { // to be changed for each user id: new uint8array.from(window.atob("laegmlkjnrlkgnamlafalfka="), c=>c.charcodeat(0)); name: "jdoe@example.com", displayname: "john doe", icon: "https://gravatar.com/avatar/jdoe.png" }, pubkeycredparams: [ { ...
PublicKeyCredentialRequestOptions.challenge - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api...
PublicKeyCredentialRequestOptions.rpId - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]), rpid: "example.com" // will only work if the current domain // is something like foo.example.com }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { cons...
PublicKeyCredentialRequestOptions.timeout - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]), timeout: 6000 // wait a minute for the fetching operation // and maybe fail if it takes longer }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.er...
PublicKeyCredentialRequestOptions.userVerification - Web APIs
examples var options = { userverification: "preferred", challenge: new uint8array([/* bytes sent from the server */]), }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api...
PushManager.registrations() - Web APIs
if the method call is successful, the request's result will be an array of pushregistration objects.
PushManager.subscribe() - Web APIs
applicationserverkey: a base64-encoded domstring or arraybuffer containing an ecdsa p-256 public key that the push server will use to authenticate your application server.
PushManager - Web APIs
properties pushmanager.supportedcontentencodings returns an array of supported content codings that can be used to encrypt the payload of a push message.
PushMessageData.json() - Web APIs
this could be anything that can be represented by json — an object, an array, a string, a number...
PushMessageData - Web APIs
methods pushmessagedata.arraybuffer() extracts the data as an arraybuffer object.
PushSubscription - Web APIs
methods pushsubscription.getkey() returns an arraybuffer which contains the client's public key, which can then be sent to a server and used in encrypting push message data.
RTCDataChannel.send() - Web APIs
this may be a usvstring, a blob, an arraybuffer, or an arraybufferview.
RTCDataChannel - Web APIs
values allowed by the websocket.binarytype property are also permitted here: "blob" if blob objects are being used or "arraybuffer" if arraybuffer objects are being used.
RTCIceServer.url - Web APIs
WebAPIRTCIceServerurl
mypeerconnection = new rtcpeerconnection({ iceservers: [ { url: "stun:stunserver.example.org" } ] }); unfortunately, the only way to tell ice that the server has a backup domain name of stunserver2.example.org is to add a new entry to the iceservers array for it.
RTCIceServers.urls - Web APIs
WebAPIRTCIceServerurls
syntax var iceserver = { urls = iceserverurl | [ url1, ..., urln ], username: "webrtc", // optional credential: "turnpassword" // optional }; iceservers.push(iceserver); the value of this property may be specified as a single url or as an array of multiple urls.
RTCPeerConnection.generateCertificate() - Web APIs
example rtcpeerconnection.generatecertificate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]) }).then(function(cert) { var pc = new rtcpeerconnection({certificates: [cert]}); }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'generatecertificate()' in that specification.
RTCPeerConnection.getTransceivers() - Web APIs
return value an array of the rtcrtptransceiver objects representing the transceivers handling sending and receiving all media on the rtcpeerconnection.
RTCRtpCodecCapability - Web APIs
an array of objects of this type is returned in the codecs property of the rtcrtpcapabilities object returned in response to a call to either of the static functions rtcrtpsender.getcapabilities() or rtcrtpreceiver.getcapabilities().
RTCRtpSendParameters.encodings - Web APIs
syntax sendparameters.encodings = encodingparameterlist; encodingparameterlist = sendparameters.encodings; value an array of objects conforming to the rtcrtpencodingparameters dictionary, each of which contains properties which provide settings and parameters that describe and configure a single codec that could be used to encode the track.
RTCRtpSendParameters - Web APIs
encodings an array of rtcrtpencodingparameters objects, each specifying the parameters for a single codec that could be used to encode the track's media.
RTCRtpSender.setParameters() - Web APIs
encodings an array of rtcrtpencodingparameters objects, each specifying the parameters for a single codec that could be used to encode the track's media.
RTCRtpTransceiver.setCodecPreferences() - Web APIs
syntax rtcrtptransceiver.setcodecpreferences(codecs) parameters codecs an array of rtcrtpcodeccapability objects, in order of preference, each providing the parameters for one of the transceiver's supported codecs.
RTCTrackEvent() - Web APIs
streams optional an array of mediastream objects representing each of the streams that comprise the event's corresponding track.
RTCTrackEventInit - Web APIs
streams optional an array of mediastream objects representing each of the streams that comprise the event's corresponding track.
ReadableByteStreamController.enqueue() - Web APIs
exceptions typeerror the source object is not a readablebytestreamcontroller, or the stream cannot be read for some other reason, or the chunk is not an object, or the chunk's internal array buffer is non-existant or detached.
ReadableStream.ReadableStream() - Web APIs
with this turned on, the stream implementation will automatically allocate an arraybuffer with a size of the given integer, and the consumer can also use a default reader.
ReadableStream.getReader() - Web APIs
if (done) { console.log("stream complete"); para.textcontent = value; return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'received ' + charsreceived + ' characters so far.
ReadableStreamBYOBRequest.respond() - Web APIs
exceptions typeerror the source object is not a readablestreambyobrequest, or there is no associated controller, or the associated internal array buffer is detached.
ReadableStreamBYOBRequest.respondWithNewView() - Web APIs
exceptions typeerror the source object is not a readablestreambyobrequest, or there is no associated controller, or the associated internal array buffer is non-existant or detached.
ReadableStreamBYOBRequest.view - Web APIs
syntax var view = readablestreambyobrequestinstance.view; value a typed array representing the destination region to which the controller can write generated data.
ReadableStreamBYOBRequest - Web APIs
a view, as mentioned below, refers to a typed array representing the destination region to which the associated readablebytestreamcontroller controller can write generated data.
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
if (done) { console.log("stream complete"); para.textcontent = result; return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'received ' + charsreceived + ' characters so far.
ReadableStreamDefaultReader.cancel() - Web APIs
if (done) { console.log("stream complete"); reader.cancel(); para.textcontent = result; return; } // value for fetch streams is a uint8array charsreceived += value.length; const chunk = value; let listitem = document.createelement('li'); listitem.textcontent = 'received ' + charsreceived + ' characters so far.
RelativeOrientationSensor - Web APIs
model.quaternion.fromarray(sensor.quaternion).inverse(); }); sensor.addeventlistener('error', error => { if (event.error.name == 'notreadableerror') { console.log("sensor is not available."); } }); sensor.start(); permissions example using orientation sensors requires requsting permissions for multiple device sensors.
Report - Web APIs
WebAPIReport
t innerlist = document.createelement('ul'); listitem.appendchild(innerlist); list.appendchild(listitem); for (let key in reports[i].body) { let innerlistitem = document.createelement('li'); let keyvalue = reports[i].body[key]; innerlistitem.textcontent = key + ': ' + keyvalue; innerlist.appendchild(innerlistitem); } } } the reports parameter contains an array of all the reports in the observer's report queue.
ReportingObserver() - Web APIs
the available options are: types: an array of strings representing the types of report to be collected by this observer.
ReportingObserver.takeRecords() - Web APIs
syntax reportingobserverinstance.takerecords() return value an array of report objects.
ReportingObserverOptions - Web APIs
properties types an array of strings representing the types of report to be collected by this observer.
ResizeObserver() - Web APIs
the function is called with two parameters: entries an array of resizeobserverentry objects that can be used to access the new dimensions of the element after each change.
ResizeObserverEntry.contentBoxSize - Web APIs
the contentboxsize read-only property of the resizeobserverentry interface returns an array containing the new content box size of the observed element when the callback is run.
RsaHashedKeyGenParams - Web APIs
publicexponent a uint8array.
RsaOaepParams - Web APIs
label optional a buffersource — an array of bytes that does not itself need to be encrypted but which should be bound to the ciphertext.
SVGLengthList - Web APIs
note: starting in gecko 5.0,the svglengthlist dom interface is now indexable and can be accessed like arrays interface overview also implement none methods void clear() svglength initialize(in svglength newitem) svglength getitem(in unsigned long index) svglength insertitembefore(in svglength newitem, in unsigned long index) svglength replaceitem(in svglength newitem, in unsigned long index) svglength removeitem(in unsigned long index) svglength appenditem(in svglength newitem) properties ...
SVGNumberList - Web APIs
note: starting in gecko 5.0,the svgnumberlist dom interface is now indexable and can be accessed like arrays.
SVGTransformList - Web APIs
note: starting in gecko 9.0,the svgtransformlist dom interface is now indexable and can be accessed like arrays interface overview also implement none methods void clear() svgtransform initialize(in svgtransform newitem) svgtransform getitem(in unsigned long index) svgtransform insertitembefore(in svgtransform newitem, in unsigned long index) svgtransform replaceitem(in svgtransform newitem, in unsigned long index) svgtransform removeitem(in unsigned long index) svgtransform appenditem(in ...
ScriptProcessorNode.bufferSize - Web APIs
octx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // ...
ScriptProcessorNode.onaudioprocess - Web APIs
octx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { ...
ScriptProcessorNode - Web APIs
octx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; }, function(e){"error with decoding audio data" + e.err}); } request.send(); } // give the node a function to process audio events scriptnode.onaudioprocess = function(audioprocessingevent) { // ...
Selection.getRangeAt() - Web APIs
example let ranges = []; sel = window.getselection(); for(let i = 0; i < sel.rangecount; i++) { ranges[i] = sel.getrangeat(i); } /* each item in the ranges array is now * a range object representing one of the * ranges in the current selection */ specifications specification status comment selection apithe definition of 'selection: getrangeat()' in that specification.
ServiceWorkerMessageEvent.ServiceWorkerMessageEvent() - Web APIs
ports: an array containing the messageport objects connected to the channel sending the message.
ServiceWorkerMessageEvent - Web APIs
serviceworkermessageevent.ports read only returns an array of messageport objects.
ServiceWorkerRegistration - Web APIs
serviceworkerregistration.getnotifications() returns a promise that resolves to an array of notification objects.
ShadowRoot - Web APIs
documentorshadowroot.elementsfrompoint() returns an array of all elements at the specified coordinates.
SourceBufferList: indexed property getter - Web APIs
the indexed property getter of the sourcebufferlist interface allows the sourcebuffer objects in the list to be accessed with an array operator (i.e.
SpeechGrammarList.item() - Web APIs
the item getter of the speechgrammarlist interface is a standard getter — it allows individual speechgrammar objects to be retrieved from the speechgrammarlist using array syntax.
SpeechGrammarList - Web APIs
methods speechgrammarlist.item() standard getter — allows individual speechgrammar objects to be retrieved from the speechgrammarlist using array syntax.
SpeechSynthesis.getVoices() - Web APIs
return value a list (array) of speechsynthesisvoice objects.
StorageQuota.supportedTypes - Web APIs
syntax var storagetypes = storagequota.supportedtypes value a frozen array of available storage types.
StyleSheet.media - Web APIs
WebAPIStyleSheetmedia
it is a read-only, array-like medialist object and can be removed with deletemedium() and added with appendmedium().
SubtleCrypto.decrypt() - Web APIs
return value result is a promise that fulfills with an arraybuffer containing the plaintext.
SyncManager.getTags() - Web APIs
}) returns a promise that resolves to an array of domstrings containing developer-defined identifiers for syncmanager registrations.
TextTrack: cuechange event - Web APIs
bubbles no cancelable no interface event event handler property globaleventhandlers.oncuechange examples on the texttrack you can set up a listener for the cuechange event on a texttrack using the addeventlistener() method: track.addeventlistener('cuechange', function () { let cues = track.activecues; // array of current cues }); or you can just set the oncuechange event handler property: track.oncuechange = function () { let cues = track.activecues; // array of current cues } on the track element the underlying texttrack, indicated by the track property, receives a cuechange event every time the currently-presented cue is changed.
TextTrackList.length - Web APIs
each track can be accessed by treating the texttracklist as an array of objects of type texttrack.
TextTrackList - Web APIs
the individual tracks can be accessed using array syntax or functions such as foreach() for example.
TrackDefault.kinds - Web APIs
syntax var mykinds = trackdefault.kinds; value an array of domstrings.
TrackDefaultList.TrackDefault() - Web APIs
the trackdefault() getter method of the trackdefaultlist interface allows the trackdefault objects in the list to be accessed with an array operator (i.e.
TrackDefaultList.TrackDefaultList() - Web APIs
syntax var trackdefaultlist = new trackdefaultlist(trackdefaults); parameters trackdefaults a sequence (array) of trackdefault objects.
TrackDefaultList - Web APIs
trackdefaultlist.trackdefault() this getter allows the trackdefault objects in the list to be accessed with an array operator (i.e.
Transferable - Web APIs
the arraybuffer, messageport, imagebitmap and offscreencanvas types implement this interface.
USB.requestDevice() - Web APIs
WebAPIUSBrequestDevice
syntax usb.requestdevice([filters]) parameters filters an array of filter objects for possible devices you would like to pair.
USB - Web APIs
WebAPIUSB
methods usb.getdevices() returns a promise that resolves with an array of usbdevice objects for paired attached devices.
USBAlternateInterface - Web APIs
usbalternateinterface.endpointsread only returns an array containing instances of the usbendpoint interface describing each of the endpoints that are part of this interface.
USBConfiguration - Web APIs
usbconfiguration.interfacesread only returns an array containing instances of the usbinterface describing each interface supported by this configuration.
USBDevice.controlTransferOut() - Web APIs
data a typedarray containing the data that will be transfered to the device.
USBDevice.isochronousTransferIn() - Web APIs
packetlengths an array of lengths for the packets being received.
USBDevice.transferOut() - Web APIs
data a typedarray containing the data to send to the device.
USBDevice - Web APIs
WebAPIUSBDevice
usbdevice.configurations read only an array of device-specific interfaces for controlling a paired usb device.
USBInterface - Web APIs
usbinterface.alternatesread only returns an array containing instances of the usbalternateinterface interface describing each of the alternative configurations possible for this interface.
USBIsochronousOutTransferResult - Web APIs
properties usbisochronousouttransferresult.packetsread only returns an array of usbisochronousouttransferpacket objects containing the result of each request to send a packet to the device.
VideoTrack - Web APIs
usage notes to get a videotrack for a given media element, use the element's videotracks property, which returns a videotracklist object from which you can get the individual tracks contained in the media: var el = document.queryselector("video"); var tracks = el.videotracks; you can then access the media's individual tracks using either array syntax or functions such as foreach().
VideoTrackList.length - Web APIs
each track can be accessed by treating the videotracklist as an array of objects of type videotrack.
VideoTrackList - Web APIs
the individual tracks can be accessed using array syntax or functions such as foreach() for example.
WEBGL_depth_texture - Web APIs
the pixels parameter now accepts an arraybufferview of type uint16array and uint32array.
WEBGL_draw_buffers.drawBuffersWEBGL() - Web APIs
syntax void gl.getextension('webgl_draw_buffers').drawbufferswebgl(buffers); parameters buffers an array of glenum constants defining drawing buffers.
WEBGL_draw_buffers - Web APIs
examples enabling the extension: var ext = gl.getextension('webgl_draw_buffers'); binding multiple textures (to a tx[] array) to different framebuffer color attachments: var fb = gl.createframebuffer(); gl.bindframebuffer(gl.framebuffer, fb); gl.framebuffertexture2d(gl.framebuffer, ext.color_attachment0_webgl, gl.texture_2d, tx[0], 0); gl.framebuffertexture2d(gl.framebuffer, ext.color_attachment1_webgl, gl.texture_2d, tx[1], 0); gl.framebuffertexture2d(gl.framebuffer, ext.color_attachment2_webgl, gl.texture_2d, tx[2]...
WaveShaperNode.oversample - Web APIs
amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } return curve; }; ...
WebGL2RenderingContext.beginTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.drawarrays(gl.triangles, 0, 3); specifications specification status comment webgl 2.0the definition of 'begintransformfeedback' in that specification.
WebGL2RenderingContext.copyTexSubImage3D() - Web APIs
gl.texture_2d_array: a two-dimensional array texture.
WebGL2RenderingContext.drawBuffers() - Web APIs
syntax void gl.drawbuffers(buffers); parameters buffers an array of glenum specifying the buffers into which fragment colors will be written.
WebGL2RenderingContext.endTransformFeedback() - Web APIs
examples var transformfeedback = gl.createtransformfeedback(); gl.bindtransformfeedback(gl.transform_feedback, transformfeedback); gl.begintransformfeedback(gl.triangles); gl.drawarrays(gl.triangles, 0, 3); gl.endtransformfeedback(); specifications specification status comment webgl 2.0the definition of 'endtransformfeedback' in that specification.
WebGL2RenderingContext.getActiveUniformBlockParameter() - Web APIs
gl.uniform_block_active_uniform_indices: returns a uint32array indicating the list of active uniforms in the uniform block.
WebGL2RenderingContext.invalidateFramebuffer() - Web APIs
attachments an array of glenum specifying the attachment points to invalidate.
WebGL2RenderingContext.invalidateSubFramebuffer() - Web APIs
attachments an array of glenum specifying the attachment points to invalidate.
WebGL2RenderingContext.pauseTransformFeedback() - Web APIs
gl.resumetransformfeedback(); gl.drawarrays(gl.triangles, 0, 3); gl.endtransformfeedback(); specifications specification status comment webgl 2.0the definition of 'pausetransformfeedback' in that specification.
WebGL2RenderingContext.resumeTransformFeedback() - Web APIs
gl.resumetransformfeedback(); gl.drawarrays(gl.triangles, 0, 3); gl.endtransformfeedback(); specifications specification status comment webgl 2.0the definition of 'resumetransformfeedback' in that specification.
WebGL2RenderingContext.transformFeedbackVaryings() - Web APIs
varyings an array of domstring specifying the the names of the varying variables to use.
WebGL2RenderingContext.uniform[1234][uif][v]() - Web APIs
a uint32array for unsigned integer vector methods (methods with uiv).
WebGL2RenderingContext.uniformMatrix[234]x[234]fv() - Web APIs
data a float32array of float values.
WebGL2RenderingContext.vertexAttribI4[u]i[v]() - Web APIs
value a uint32array/int32array or sequences of gluint/ glint for integer vector vertex attribute values.
WebGLProgram - Web APIs
// use the program gl.useprogram(program); // bind existing attribute data gl.bindbuffer(gl.array_buffer, buffer); gl.enablevertexattribarray(attributelocation); gl.vertexattribpointer(attributelocation, 3, gl.float, false, 0, 0); // draw a single triangle gl.drawarrays(gl.triangles, 0, 3); deleting the program if there is an error linking the program or you wish to delete an existing program, then it is as simple as running webglrenderingcontext.deleteprogram().
WebGLRenderingContext.colorMask() - Web APIs
examples gl.colormask(true, true, true, false); to get the current color mask, query the color_writemask constant which returns an array.
WebGLRenderingContext.depthRange() - Web APIs
examples gl.depthrange(0.2, 0.6); to check the current depth range, query the depth_range constant which returns a float32array gl.getparameter(gl.depth_range); // float32array[0.2, 0.6] specifications specification status comment webgl 1.0the definition of 'depthrange' in that specification.
WebGLRenderingContext.getAttachedShaders() - Web APIs
return value an array of webglshader objects that are attached to the given webglprogram.
WebGLRenderingContext.lineWidth() - Web APIs
returns a float32array.
WebGLRenderingContext.uniformMatrix[234]fv() - Web APIs
value a float32array or sequence of glfloat values.
Hello GLSL - Web APIs
" + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.vertexattribpointer(0, 1, gl.float, false, 0, 0); } function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer); if (program) gl.deleteprogram(program); } function getrenderingconte...
Textures from code - Web APIs
" + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array([0.0, 0.0]), gl.static_draw); gl.vertexattribpointer(0, 2, gl.float, false, 0, 0); } function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buf...
Data in WebGL - Web APIs
WebAPIWebGL APIData
// yellow vec4( 0.0, 1.0, 0.0, 1.0 ), // green vec4( 0.0, 0.0, 0.0, 1.0 ), // black vec4( 1.0, 0.0, 0.0, 1.0 ), // red vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow vec4( 0.0, 1.0, 0.0, 1.0 ), // green ]; var cbuffer = gl.createbuffer(); //continued //create buffer to store colors and reference it to "vcolor" which is in glsl gl.bindbuffer( gl.array_buffer, cbuffer ); gl.bufferdata( gl.array_buffer, flatten(vertexcolors), gl.static_draw ); var vcolor = gl.getattriblocation( program, "vcolor" ); gl.vertexattribpointer( vcolor, 4, gl.float, false, 0, 0 ); gl.enablevertexattribarray( vcolor ); //glsl attribute vec4 vcolor; void main() { fcolor = vcolor; } varyings varyings are variables that are declared by the ver...
Animating textures in WebGL - Web APIs
const level = 0; const internalformat = gl.rgba; const width = 1; const height = 1; const border = 0; const srcformat = gl.rgba; const srctype = gl.unsigned_byte; const pixel = new uint8array([0, 0, 255, 255]); // opaque blue gl.teximage2d(gl.texture_2d, level, internalformat, width, height, border, srcformat, srctype, pixel); // turn off mips and set wrapping to clamp to edge so it // will work regardless of the dimensions of the video.
Taking still photos with WebRTC - Web APIs
when the promise is fulfilled with an array of mediadeviceinfo objects describing the available devices, find the ones that you want to allow and specify the corresponding deviceid or deviceids in the mediatrackconstraints object passed into getusermedia().
Using DTMF with WebRTC - Web APIs
function handlereceivertrackevent(event) { audio.srcobject = event.streams[0]; } function handlereceiveraddstreamevent(event) { audio.srcobject = event.stream; } the track event includes a streams property containing an array of the streams the track is a member of (one track can be part of many streams).
WebRTC Statistics API - Web APIs
the webrtc api has a vast array of statistics available, covering the entire breadth of the webrtc connectivity system, from sender to receiver and peer to peer.
WebSocket() - Web APIs
protocols optional either a single protocol string or an array of protocol strings.
WebSocket.binaryType - Web APIs
"arraybuffer" if arraybuffer objects are used.
Writing a WebSocket server in C# - Web APIs
decoding algorithm di = ei xor m(i mod 4) where d is the decoded message array, e is the encoded message array, m is the mask byte array, and i is the index of the message byte to decode.
WebXR performance guide - Web APIs
but it's inefficient, because it allocates as local variables a number of things, including at least two matrices, an array of vertices, and more.
Rendering and the WebXR frame animation callback - Web APIs
we iterate over the views within the viewer poses's views array.
WebXR Device API - Web APIs
included is an array of xrview objects, each representing one perspective on the scene.
Using the Web Animations API - Web APIs
representing keyframes the first thing we need is to create a keyframe object corresponding to our css @keyframes block: var alicetumbling = [ { transform: 'rotate(0) translate3d(-50%, -50%, 0)', color: '#000' }, { color: '#431236', offset: 0.3}, { transform: 'rotate(360deg) translate3d(-50%, -50%, 0)', color: '#000' } ]; here we’re using an array containing multiple objects.
Web Animations API Concepts - Web APIs
animation the animation model can be thought of as an array of snapshots of what the animation could look like at any given time, lined up along the duration of the animation.
Web Audio API - Web APIs
sources provide arrays of sound intensities (samples) at very small timeslices, often tens of thousands of them per second.
Functions and classes available to Web Workers - Web APIs
in addition to the standard javascript set of functions (such as string, array, object, json, etc), there are a variety of functions available from the dom to workers.
Window.crypto - Web APIs
WebAPIWindowcrypto
javascript genrandomnumbers = function getrandomnumbers() { var array = new uint32array(10); window.crypto.getrandomvalues(array); var randtext = document.getelementbyid("myrandtext"); randtext.innerhtml = "the random numbers are: " for (var i = 0; i < array.length; i++) { randtext.innerhtml += array[i] + " "; } } html <p id="myrandtext">the random numbers are: </p> <button type="button" onclick='genrandomnumbers()'>generate 10 random numbers</butt...
Window: pageshow event - Web APIs
bubbles no cancelable no interface pagetransitionevent event handler property onpageshow examples this example sets up event handlers for events listed in the array events.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
examples self.queuemicrotask(() => { // function contents here }) taken from the queuemicrotask spec: myelement.prototype.loaddata = function (url) { if (this._cache[url]) { queuemicrotask(() => { this._setdata(this._cache[url]); this.dispatchevent(new event("load")); }); } else { fetch(url).then(res => res.arraybuffer()).then(data => { this._cache[url] = data; this._setdata(data); this.dispatchevent(new event("load")); }); } }; when queuemicrotask() isn't available the code below is basically a monkey-patch for queuemicrotask() for modern engines.
WindowOrWorkerGlobalScope - Web APIs
windoworworkerglobalscope.crossoriginisolated read only returns a boolean value that indicates whether a sharedarraybuffer can be sent via a window.postmessage() call.
WorkerGlobalScope.self - Web APIs
example if you called console.log(self); inside a worker, you will get a worker global scope of the same type as that worker object written to the console — something like the following: dedicatedworkerglobalscope { undefined: undefined, infinity: infinity, math: mathconstructor, nan: nan, intl: object…} infinity: infinity array: function array() { [native code] } arguments: null caller: null isarray: function isarray() { [native code] } length: 1 name: "array" observe: function observe() { [native code] } prototype: array[0] unobserve: function unobserve() { [native code] } __proto__: function empty() {} <function scope> arraybuffer: function arraybuffer() ...
WorkerNavigator - Web APIs
navigatorlanguage.languagesread only returns an array of domstrings representing the languages known to the user, in order of preference.
WritableStream.WritableStream() - Web APIs
onsole.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); l...
WritableStream.getWriter() - Web APIs
onsole.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); l...
WritableStream - Web APIs
onsole.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); l...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
onsole.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); l...
WritableStreamDefaultWriter.close() - Web APIs
onsole.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); l...
WritableStreamDefaultWriter.write() - Web APIs
onsole.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement('li'); l...
WritableStreamDefaultWriter - Web APIs
ll chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decoded; list.appendchild(listitem); result += decoded; resolve(); }); }, close() { var listitem = document.createelement(...
XMLHttpRequest.responseType - Web APIs
arraybuffer the response is a javascript arraybuffer containing binary data.
XRInputSource - Web APIs
profilesread only an array of domstring objects, each specifying the name of an input profile describing the preferred visual representation and behavior of this input source.
XRInputSourcesChangeEvent.added - Web APIs
syntax let addedinputs = xrinputsourceschangeevent.added; value an array of zero or more xrinputsource objects, each representing one input device added to the xr system.
XRInputSourcesChangeEventInit.added - Web APIs
new xrinputsourceschangeeventinit("inputsourceschange", inputsourceseventinit); myinputsourceschangeevent = new xrinputsourceschangeeventinit("inputsourceschange", { session: xrsession, added: addeddevicelist, removed: removeddevicelist }); value an array of zero or more xrinputsource objects, each representing one input device added to the xr system.
XRPermissionDescriptor.optionalFeatures - Web APIs
syntax xrpermissiondescriptor = { mode: xrsessionmode, requiredfeatures: reqfeaturelist, optionalfeatures: optfeaturelist }; xrpermissiondescriptor.optionalfeatures = optfeaturelist; optfeaturelist = xrpermissiondescriptor.optionalfeatures; value an array of strings taken from the xrreferencespacetype enumerated type, indicating set of features that your app would like to use, but can operate without if permission to use them isn't available.
XRPermissionDescriptor.requiredFeatures - Web APIs
syntax xrpermissiondescriptor = { mode: xrsessionmode, requiredfeatures: reqfeaturelist, optionalfeatures: optfeaturelist }; xrpermissiondescriptor.requiredfeatures = reqfeaturelist; reqfeaturelist = xrpermissiondescriptor.requiredfeatures; value an array of strings indicating the webxr features which must be available for use by the app or site.
XRPermissionStatus - Web APIs
granted an array of strings listing the names of the features for which permission has been granted as of the time at which navigator.permissions.query() was called.
XRReferenceSpaceEvent.transform - Web APIs
the scene is represented by a scene object, with all the objects in an array called objects within it.
XRSession.oninputsourceschange - Web APIs
note: the xrinputsource objects in xrsession.inputsources array are "live", so values within them are updated in-place.
XRSpace - Web APIs
WebAPIXRSpace
xrboundedreferencespace represents a reference space which may move within a region of space whose borders are defined by an array of points laid out in clockwise order along the floor to define the passable region of the space.
XRView.projectionMatrix - Web APIs
syntax let projectionmatrix = xrview.projectionmatrix; value a float32array object representing the projection matrix for the view.
msGetRegionContent - Web APIs
the msgetregioncontent returns an array of range instances corresponding to the content from the region flow that is positioned in the region.
:scope - CSS: Cascading Style Sheets
WebCSS:scope
javascript var context = document.getelementbyid('context'); var selected = context.queryselectorall(':scope > div'); document.getelementbyid('results').innerhtml = array.prototype.map.call(selected, function (element) { return '#' + element.getattribute('id'); }).join(', '); html <div id="context"> <div id="element-1"> <div id="element-1.1"></div> <div id="element-1.2"></div> </div> <div id="element-2"> <div id="element-2.1"></div> </div> </div> <p> selected elements ids : <span id="results"></span> </p> resu...
Detecting CSS animation support - CSS: Cascading Style Sheets
we create an array of browser prefixes to loop over and we set pfx to an empty string.
Border-image generator - CSS: Cascading Style Sheets
ckimage(e) { if (e.target.classname === 'image') { selected = e.target; selected.setattribute('selected', 'true'); loadremoteimage(e.target.src); imgstate = e.target.getattribute('data-stateid'); } }; var loadimagestate = function loadimagestate(stateid) { if (properties[stateid] === undefined) return; var prop = properties[stateid]; var topic; var unit_array; var value_array; for (var i in topics) { for (var j=0; j<4; j++) { topic = topics[i] + '-' + positions[j]; unit_array = topics[i] + '_units'; value_array = topics[i] + '_values'; inputslidermanager.setvalue(topic, prop[value_array][j]); dropdownmanager.setvalue(topic, prop[unit_array][j]); } } buttonmanager.setvalue('slice-fill', prop['fill']); d...
CSS Properties Reference - CSS: Cascading Style Sheets
t marginright margin-top margintop overflow overflow padding padding padding-bottom paddingbottom padding-left paddingleft padding-right paddingright padding-top paddingtop page-break-after pagebreakafter page-break-before pagebreakbefore position position stroke-dasharray strokedasharray stroke-dashoffset strokedashoffset stroke-width strokewidth text-align textalign text-decoration textdecoration text-indent textindent text-transform texttransform top top vertical-align verticalalign visibility visibility width width z-index zinde...
animation - CSS: Cascading Style Sheets
WebCSSanimation
ames slidein { from { transform: scalex(0); } to { transform: scalex(1); } } .a1 { animation: 3s ease-in 1s 2 reverse both paused slidein; } .a2 { animation: 3s linear 1s slidein; } .a3 { animation: 3s slidein; } .animation { background: #3f87a6; width: 100%; height: calc(100% - 1.5em); transform-origin: left center; } window.addeventlistener('load', function () { var animation = array.from(document.queryselectorall('.animation')); var button = array.from(document.queryselectorall('button')); function togglebutton (btn, type) { btn.classlist.remove('play', 'pause', 'restart'); btn.classlist.add(type); btn.title = type.touppercase(type); } function playpause (i) { var btn = button[i]; var anim = animation[i]; if (btn.classlist.contains('pla...
Guide to Web APIs - Developer guides
WebGuideAPI
the web includes a wide array of apis that can be used from javascript to build increasingly more powerful and capable applications, running either on the web, locally, or through technology such as node.js, on a server.
Adding captions and subtitles to HTML5 video - Developer guides
with all the other buttons, one of the first things we need to do is store a handle to the subtitles' button: var subtitles = document.getelementbyid('subtitles'); we also initially turn off all subtitles, in case the browser turns any of them on by default: for (var i = 0; i < video.texttracks.length; i++) { video.texttracks[i].mode = 'hidden'; } the video.texttracks property contains an array of all the text tracks attached to the video.
Audio and Video Delivery - Developer guides
web audio api var context; var request; var source; try { context = new audiocontext(); request = new xmlhttprequest(); request.open("get","http://jplayer.org/audio/mp3/riomez-01-sleep_together.mp3",true); request.responsetype = "arraybuffer"; request.onload = function() { context.decodeaudiodata(request.response, function(buffer) { source = context.createbuffersource(); source.buffer = buffer; source.connect(context.destination); // auto play source.start(0); // start was previously noteon }); }; request.send(); } catch(e) { alert('web audio api not suppo...
Index - Developer guides
WebGuideIndex
28 guide to web apis api, guide, landing, web the web includes a wide array of apis that can be used from javascript to build increasingly more powerful and capable applications, running either on the web, locally, or through technology such as node.js, on a server.
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
WebHTMLElementiframe
scripting inline frames, like <frame> elements, are included in the window.frames pseudo-array.
<input type="checkbox"> - HTML: Hypertext Markup Language
WebHTMLElementinputcheckbox
when this string reaches the server, you need to parse it other than as an associative array, so all values, not only the last value, of interest are captured.
Preloading content with rel="preload" - HTML: Hypertext Markup Language
fetch: resource to be accessed by a fetch or xhr request, such as an arraybuffer or json file.
Proxy Auto-Configuration (PAC) file - HTTP
isplainhostname() dnsdomainis() localhostordomainis() isresolvable() isinnet() related utility functions dnsresolve() convert_addr() myipaddress() dnsdomainlevels() url/hostname based conditions shexpmatch() time based conditions weekdayrange() daterange() timerange() logging utility alert() there was one associative array (object) already defined, because at the time javascript code was unable to define it by itself: proxyconfig.bindings note: pactester (part of the pacparser package) was used to test the following syntax examples.
Introduction - JavaScript
javascript contains a standard library of objects, such as array, date, and math, and a core set of language elements such as operators, control structures, and statements.
Meta programming - JavaScript
with reflect.has() for example, you get the in operator as a function: reflect.has(object, 'assign') // true a better apply function in es5, you typically use the function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object).
Using Promises - JavaScript
art operations in parallel and wait for them all to finish like this: promise.all([func1(), func2(), func3()]) .then(([result1, result2, result3]) => { /* use result1, result2 and result3 */ }); sequential composition is possible using some clever javascript: [func1, func2, func3].reduce((p, f) => p.then(f), promise.resolve()) .then(result3 => { /* use result3 */ }); basically, we reduce an array of asynchronous functions down to a promise chain equivalent to: promise.resolve().then(func1).then(func2).then(func3); this can be made into a reusable compose function, which is common in functional programming: const applyasync = (acc,val) => acc.then(val); const composeasync = (...funcs) => x => funcs.reduce(applyasync, promise.resolve(x)); the composeasync() function will accept any numbe...
JavaScript Guide - JavaScript
s arrow functions expressions and operators assignment & comparisons arithmetic operators bitwise & logical operators conditional (ternary) operator numbers and dates number literals number object math object date object text formatting string literals string object template literals internationalization regular expressions indexed collections arrays typed arrays keyed collections map weakmap set weakset working with objects objects and properties creating objects defining methods getter and setter details of the object model prototype-based oop creating object hierarchies inheritance promises guarantees chaining error propagation composition timing iterators and generators ...
JavaScript technologies overview - JavaScript
a prototype-based inheritance mechanism built-in objects and functions (json, math, array.prototype methods, object introspection methods, etc.) strict mode browser support as of october 2016, the current versions of the major web browsers implement ecmascript 5.1 and ecmascript 2015, but older versions (still in use) implement ecmascript 5 only.
The legacy Iterator protocol - JavaScript
simple example with the old protocol function makeiterator(array){ var nextindex = 0; return { next: function(){ if(nextindex < array.length){ return array[nextindex++]; else throw new stopiteration(); } } } var it = makeiterator(['yo', 'ya']); console.log(it.next()); // 'yo' console.log(it.next()); // 'ya' try{ console.log(it.next()); } catch(e){ if(e instanceof stopitera...
TypeError: property "x" is non-configurable and can't be deleted - JavaScript
'use strict'; var obj = object.freeze({name: 'elsa', score: 157}); delete obj.score; // typeerror 'use strict'; var obj = {}; object.defineproperty(obj, 'foo', {value: 2, configurable: false}); delete obj.foo; // typeerror 'use strict'; var frozenarray = object.freeze([0, 1, 2]); frozenarray.pop(); // typeerror there are also a few non-configurable properties built into javascript.
SyntaxError: JSON.parse: bad parsing - JavaScript
rt is missing a number syntaxerror: json.parse: unexpected end of data syntaxerror: json.parse: unexpected keyword syntaxerror: json.parse: unexpected character syntaxerror: json.parse: end of data while reading object contents syntaxerror: json.parse: expected property name or '}' syntaxerror: json.parse: end of data when ',' or ']' was expected syntaxerror: json.parse: expected ',' or ']' after array element syntaxerror: json.parse: end of data when property name was expected syntaxerror: json.parse: expected double-quoted property name syntaxerror: json.parse: end of data after property name when ':' was expected syntaxerror: json.parse: expected ':' after property name in object syntaxerror: json.parse: end of data after property value in object syntaxerror: json.parse: expected ',' or '}' ...
SyntaxError: missing variable name - JavaScript
var x, y = "foo", var x, = "foo" var first = document.getelementbyid('one'), var second = document.getelementbyid('two'), // syntaxerror: missing variable name the fixed version: var x, y = "foo"; var x = "foo"; var first = document.getelementbyid('one'); var second = document.getelementbyid('two'); arrays array literals in javascript need square brackets around the values.
TypeError: "x" is not a constructor - JavaScript
there are many global objects, like string or array, which are constructable using new.
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
var foo = { baz: "bar" }; "bar" in foo; // false "pi" in math; // true "pi" in math; // false searching in arrays be careful when using the in operator to search in array objects.
Default parameters - JavaScript
function append(value, array = []) { array.push(value) return array } append(1) // [1] append(2) // [2], not [1, 2] this even applies to functions and variables: function callsomething(thing = something()) { return thing } let numberoftimescalled = 0 function something() { numberoftimescalled += 1 return numberoftimescalled } callsomething() // 1 callsomething() // 2 earlier parameters are available to ...
arguments[@@iterator]() - JavaScript
the initial value of the @@iterator property is the same function object as the initial value of the array.prototype.values property.
getter - JavaScript
examples defining a getter on new objects in object initializers this will create a pseudo-property latest for object obj, which will return the last array item in log.
Atomics.isLockFree() - JavaScript
it returns true, if the given size is one of the bytes_per_element property of integer typedarray types.
BigInt - JavaScript
const expected = 4n / 2n // ↪ 2n const rounded = 5n / 2n // ↪ 2n, not 2.5n comparisons a bigint is not strictly equal to a number, but it is loosely so: 0n === 0 // ↪ false 0n == 0 // ↪ true a number and a bigint may be compared as usual: 1n < 2 // ↪ true 2n > 1 // ↪ true 2 > 2 // ↪ false 2n > 2 // ↪ false 2n >= 2 // ↪ true they may be mixed in arrays and sorted: const mixed = [4n, 6, -12n, 10, 4, 0, 0n] // ↪ [4n, 6, -12n, 10, 4, 0, 0n] mixed.sort() // default sorting behavior // ↪ [ -12n, 0, 0n, 10, 4n, 4, 6 ] mixed.sort((a, b) => a - b) // won't work since subtraction will not work with mixed types // typeerror: can't convert bigint to number // sort with an appropriate numeric comparator mixed.sort((a, b) => (a < b) ?
Boolean() constructor - JavaScript
with an initial value of false var bnoparam = new boolean(); var bzero = new boolean(0); var bnull = new boolean(null); var bemptystring = new boolean(''); var bfalse = new boolean(false); creating boolean objects with an initial value of true var btrue = new boolean(true); var btruestring = new boolean('true'); var bfalsestring = new boolean('false'); var bsulin = new boolean('su lin'); var barrayproto = new boolean([]); var bobjproto = new boolean({}); specifications specification ecmascript (ecma-262)the definition of 'boolean constructor' in that specification.
DataView.prototype.getBigInt64() - JavaScript
examples using the getbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbigint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbigint64()' in that specification.
DataView.prototype.getBigUint64() - JavaScript
examples using the getbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbiguint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbiguint64()' in that specification.
DataView.prototype.getFloat32() - JavaScript
examples using the getfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat32' in that specification.
DataView.prototype.getFloat64() - JavaScript
examples using the getfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat64(0); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat64' in that specification.
DataView.prototype.getInt16() - JavaScript
examples using the getint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint16' in that specification.
DataView.prototype.getInt32() - JavaScript
examples using the getint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint32' in that specification.
DataView.prototype.getInt8() - JavaScript
examples using the getint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint8' in that specification.
DataView.prototype.getUint16() - JavaScript
examples using the getuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint16' in that specification.
DataView.prototype.getUint32() - JavaScript
examples using the getuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint32' in that specification.
DataView.prototype.getUint8() - JavaScript
examples using the getuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint8' in that specification.
DataView.prototype.setBigInt64() - JavaScript
examples using the setbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbigint64(0, 3n); dataview.getbigint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbigint64()' in that specification.
DataView.prototype.setBigUint64() - JavaScript
examples using the setbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbiguint64(0, 3n); dataview.getbiguint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbiguint64()' in that specification.
DataView.prototype.setFloat32() - JavaScript
examples using the setfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat32(1, 3); dataview.getfloat32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat32' in that specification.
DataView.prototype.setFloat64() - JavaScript
examples using the setfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat64(0, 3); dataview.getfloat64(0); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat64' in that specification.
DataView.prototype.setInt16() - JavaScript
examples using the setint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint16(1, 3); dataview.getint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint16' in that specification.
DataView.prototype.setInt32() - JavaScript
examples using the setint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint32(1, 3); dataview.getint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint32' in that specification.
DataView.prototype.setInt8() - JavaScript
examples using the setint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint8(1, 3); dataview.getint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint8' in that specification.
DataView.prototype.setUint16() - JavaScript
examples using the setuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint16(1, 3); dataview.getuint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint16' in that specification.
DataView.prototype.setUint32() - JavaScript
examples using the setuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint32(1, 3); dataview.getuint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint32' in that specification.
DataView.prototype.setUint8() - JavaScript
examples using the setuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint8(1, 3); dataview.getuint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint8' in that specification.
Date.prototype.toLocaleTimeString() - JavaScript
cation may want to use utc and make that visible var options = { timezone: 'utc', timezonename: 'short' }; console.log(date.tolocaletimestring('en-us', options)); // → "3:00:00 am gmt" // sometimes even the us needs 24-hour time console.log(date.tolocaletimestring('en-us', { hour12: false })); // → "19:00:00" // show only hours and minutes, use options with the default locale - use an empty array console.log(date.tolocaletimestring([], { hour: '2-digit', minute: '2-digit' })); // → "20:01" specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tolocaletimestring' in that specification.
Error.prototype.stack - JavaScript
while an object (or array, etc.) would appear in the converted form "[object object]", and as such could not be evaluated back into the actual objects, scalar values could be retrieved (though it may be — it is still possible in firefox 14 — easier to use arguments.callee.caller.arguments, as could the function name be retrieved by arguments.callee.caller.name).
Function.arguments - JavaScript
the function.arguments property refers to an an array-like object corresponding to the arguments passed to a function.
InternalError - JavaScript
example cases are mostly when something is too large, e.g.: "too many switch cases", "too many parentheses in regular expression", "array initializer too large", "too much recursion".
Intl.Collator() constructor - JavaScript
a string with a bcp 47 language tag, or an array of such strings.
Intl.Collator - JavaScript
static methods intl.collator.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Intl.DateTimeFormat() constructor - JavaScript
syntax new intl.datetimeformat([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings.
Intl.DateTimeFormat.prototype.formatRangeToParts() - JavaScript
syntax intl.datetimeformat.prototype.formatrangetoparts(startdate, enddate) examples basic formatrangetoparts usage this method receives two dates and returns an array of objects containing the locale-specific tokens representing each part of the formatted date range.
Intl.DisplayNames() constructor - JavaScript
syntax new intl.displaynames([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings.
Intl.DisplayNames - JavaScript
static methods intl.displaynames.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Intl.ListFormat() constructor - JavaScript
a string with a bcp 47 language tag, or an array of such strings.
Intl​.ListFormat.prototype​.format() - JavaScript
syntax listformat.format([list]); parameters list an iterable object, such as an array return value a language-specific formatted string representing the elements of the list description the format() method returns a string that has been formatted based on parameters provided in the intl.listformat object.
Intl.NumberFormat() constructor - JavaScript
syntax new intl.numberformat([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings.
Intl.PluralRules() constructor - JavaScript
a string with a bcp 47 language tag, or an array of such strings.
Intl.PluralRules - JavaScript
static methods intl.pluralrules.supportedlocalesof() returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
Intl.RelativeTimeFormat() constructor - JavaScript
a string with a bcp 47 language tag, or an array of such strings.
Intl - JavaScript
multiple locales may be specified (and a best-supported locale determined by evaluating each of them in order and comparing against the locales supported by the implementation) by passing an array (or array-like object, with a length property and corresponding indexed elements) whose elements are either intl.locale objects or values that convert to unicode bcp 47 locale identifier strings.
JSON.parse() - JavaScript
return value the object, array, string, number, boolean, or null value corresponding to the given json text.
NaN - JavaScript
// true valueisnan(number.nan); // true however, do note the difference between isnan() and number.isnan(): the former will return true if the value is currently nan, or if it is going to be nan after it is coerced to a number, while the latter will return true only if the value is currently nan: isnan('hello world'); // true number.isnan('hello world'); // false additionally, some array methods cannot find nan, while others can.
Object.create() - JavaScript
be aware of, also, that using object.entries() on an object created via object.create() will result in an empty array being returned.
Object.defineProperty() - JavaScript
when temperature property is set, the archive array gets a log entry.
Object.prototype.hasOwnProperty() - JavaScript
if an object is an array, hasownproperty method can check whether an index exists.
Object.prototype.propertyIsEnumerable() - JavaScript
examples a basic use of propertyisenumerable the following example shows the use of propertyisenumerable on objects and arrays: var o = {}; var a = []; o.prop = 'is enumerable'; a[0] = 'is enumerable'; o.propertyisenumerable('prop'); // returns true a.propertyisenumerable(0); // returns true user-defined vs.
Object.setPrototypeOf() - JavaScript
ochain : new ochain.constructor(ochain); for (var o1st = this.getprototypeof(o2nd); o1st !== object.prototype && o1st !== function.prototype; o1st = this.getprototypeof(o2nd) ) { o2nd = o1st; } if (oproto.constructor === string) { onewproto = function.prototype; oreturn = function.apply(null, array.prototype.slice.call(arguments, 1)); this.setprototypeof(oreturn, olast); } this.setprototypeof(o2nd, onewproto); return oreturn; } usage first example: appending a chain to a prototype function mammal() { this.ismammal = 'yes'; } function mammalspecies(smammalspecies) { this.species = smammalspecies; } mammalspecies.prototype = new mammal(); mammalspecies.prototype.construct...
Object.prototype.toSource() - JavaScript
these objects are: array.prototype.tosource() — array object.
Promise.resolve() - JavaScript
examples using the static promise.resolve method promise.resolve('success').then(function(value) { console.log(value); // "success" }, function(value) { // not called }); resolving an array var p = promise.resolve([1,2,3]); p.then(function(v) { console.log(v[0]); // 1 }); resolving another promise var original = promise.resolve(33); var cast = promise.resolve(original); cast.then(function(value) { console.log('value: ' + value); }); console.log('original === cast ?
handler.getPrototypeOf() - JavaScript
st handler = { getprototypeof(target) { console.log(target === obj); // true console.log(this === handler); // true return proto; } }; const p = new proxy(obj, handler); console.log(object.getprototypeof(p) === proto); // true five ways to trigger the getprototypeof trap const obj = {}; const p = new proxy(obj, { getprototypeof(target) { return array.prototype; } }); console.log( object.getprototypeof(p) === array.prototype, // true reflect.getprototypeof(p) === array.prototype, // true p.__proto__ === array.prototype, // true array.prototype.isprototypeof(p), // true p instanceof array // true ); two kinds of exceptions const obj = {}; const p = new proxy(obj,...
Proxy() constructor - JavaScript
it can be any sort of object, including a native array, a function, or even another proxy.
Proxy.revocable() - JavaScript
it can be any sort of object, including a native array, a function, or even another proxy.
RangeError - JavaScript
this can be encountered when: passing a value that is not one of the allowed string values to string.prototype.normalize(), or when attempting to create an array of an illegal length with the array constructor, or when passing bad values to the numeric methods number.prototype.toexponential(), number.prototype.tofixed() or number.prototype.toprecision().
Reflect.construct() - JavaScript
argumentslist an array-like object specifying the arguments with which target should be called.
Reflect.get() - JavaScript
examples using reflect.get() // object let obj = { x: 1, y: 2 } reflect.get(obj, 'x') // 1 // array reflect.get(['zero', 'one'], 1) // "one" // proxy with a get handler let x = {p: 1}; let obj = new proxy(x, { get(t, k, r) { return k + 'bar' } }) reflect.get(obj, 'foo') // "foobar" //proxy with get handler and receiver let x = {p: 1, foo: 2}; let y = {foo: 3}; let obj = new proxy(x, { get(t, prop, receiver) { return receiver[prop] + 'bar' } }) reflect.get(obj, 'foo', y...
Reflect.set() - JavaScript
examples using reflect.set() // object let obj = {} reflect.set(obj, 'prop', 'value') // true obj.prop // "value" // array let arr = ['duck', 'duck', 'duck'] reflect.set(arr, 2, 'goose') // true arr[2] // "goose" // it can truncate an array.
Reflect - JavaScript
reflect.ownkeys(target) returns an array of the target object's own (not inherited) property keys.
RegExp.prototype[@@match]() - JavaScript
return value an array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.
RegExpInstance.lastIndex - JavaScript
console.log(re.exec('hi')); console.log(re.lastindex); returns ["", undefined], an empty array whose zeroth element is the match string.
RegExp.$1-$9 - JavaScript
you can access all parenthesized substrings through the returned array's indexes.
RegExp - JavaScript
regexp.prototype[@@split]() splits given string into an array by separating the string into substrings.
Set.prototype.forEach() - JavaScript
this is to make it consistent with other foreach() methods for map and array.
String.prototype.charAt() - JavaScript
let str = 'a\ud87e\udc04z' // we could also use a non-bmp character directly for (let i = 0, chr; i < str.length; i++) { [chr, i] = getwholecharandi(str, i) // adapt this line at the top of each loop, passing in the whole string and // the current iteration and returning an array with the individual character // and 'i' value (only changed if a surrogate pair) console.log(chr) } function getwholecharandi(str, i) { let code = str.charcodeat(i) if (number.isnan(code)) { return '' // position not found } if (code < 0xd800 || code > 0xdfff) { return [str.charat(i), i] // normal character, keeping 'i' the same } // high surrogate (could change las...
String.prototype.indexOf() - JavaScript
note: for the array method, see array.prototype.indexof().
String.prototype.link() - JavaScript
links created with the link() method become elements in the links array of the document object.
Symbol.hasInstance - JavaScript
property attributes of symbol.hasinstance writable no enumerable no configurable no examples custom instanceof behavior you could implement your custom instanceof behavior like this, for example: class myarray { static [symbol.hasinstance](instance) { return array.isarray(instance) } } console.log([] instanceof myarray); // true function myarray() { } object.defineproperty(myarray, symbol.hasinstance, { value: function(instance) { return array.isarray(instance); } }); console.log([] instanceof myarray); // true specifications specification ecmascript (ecma-262)the de...
Symbol.iterator - JavaScript
the built-in types with a @@iterator method are: array.prototype[@@iterator]() typedarray.prototype[@@iterator]() string.prototype[@@iterator]() map.prototype[@@iterator]() set.prototype[@@iterator]() see also iteration protocols for more information.
Symbol.matchAll - JavaScript
property attributes of symbol.matchall writable no enumerable no configurable no examples using symbol.matchall let re = /[0-9]+/g; let str = '2016-01-02|2019-03-07'; const numbers = { *[symbol.matchall] (str) { for (const n of str.matchall(/[0-9]+/g)) yield n[0]; } }; console.log(array.from(str.matchall(numbers))); // array ["2016", "01", "02", "2019", "03", "07"] see string.prototype.matchall() and regexp.prototype[@@matchall]() for more examples.
Symbol.split - JavaScript
property attributes of symbol.split writable no enumerable no configurable no examples custom reverse split class reversesplit { [symbol.split](string) { const array = string.split(' '); return array.reverse(); } } console.log('another one bites the dust'.split(new reversesplit())); // expected output: [ "dust", "the", "bites", "one", "another" ] specifications specification ecmascript (ecma-262)the definition of 'symbol.split' in that specification.
Symbol.toStringTag - JavaScript
property attributes of symbol.tostringtag writable no enumerable no configurable no examples default tags object.prototype.tostring.call('foo'); // "[object string]" object.prototype.tostring.call([1, 2]); // "[object array]" object.prototype.tostring.call(3); // "[object number]" object.prototype.tostring.call(true); // "[object boolean]" object.prototype.tostring.call(undefined); // "[object undefined]" object.prototype.tostring.call(null); // "[object null]" // ...
WeakMap() constructor - JavaScript
syntax new weakmap([iterable]) parameters iterable iterable is an array or other iterable object whose elements are key-value pairs (2-element arrays).
WebAssembly.Instance() constructor - JavaScript
examples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new webassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) however, the preferred way to get an instance is through the asynchronous webassembly.instantiatestreaming() function, for example like this: const importobject = { imports: { imported_func: function(arg) { console.
WebAssembly.Instance - JavaScript
examples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new webassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) the preferred way to get an instance is asynchronously, for example using the webassembly.instantiatestreaming() function like this: const importobject = { imports: { imported_func: function(arg) { console.log(arg);...
WebAssembly.Memory.prototype.buffer - JavaScript
webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); specifications specification webassembly javascript interfacethe definition of 'buffer' in that specification.
WebAssembly.Table - JavaScript
the webassembly.table() object is a javascript wrapper object — an array-like structure representing a webassembly table, which stores function references.
WebAssembly.compileStreaming() - JavaScript
exceptions if buffersource is not a typed array, a typeerror is thrown.
eval() - JavaScript
parsing json (converting strings to javascript objects) if the string you're calling eval() on contains data (for example, an array: "[1, 2, 3]"), as opposed to code, you should consider switching to json, which allows the string to use a subset of javascript syntax to represent data.
Lexical grammar - JavaScript
new in es2015 var a = 'foo', b = 'bar', c = 42; var o = {a, b, c}; // instead of var o = { a: a, b: b, c: c }; array literals see also array for more information.
Object initializer - JavaScript
in json the values can only be strings, numbers, arrays, true, false, null, or another (json) object.
Optional chaining (?.) - JavaScript
} optional chaining with expressions you can also use the optional chaining operator when accessing properties with an expression using the bracket notation of the property accessor: let nestedprop = obj?.['prop' + 'name']; optional chaining not valid on the left-hand side of an assignment let object = {}; object?.property = 1; // uncaught syntaxerror: invalid left-hand side in assignment array item access with optional chaining let arrayitem = arr?.[42]; examples basic example this example looks for the value of the name property for the member bar in a map when there is no such member.
this - JavaScript
ply(obj); // 'custom' as this in the function is set to obj this and object conversion function add(c, d) { return this.a + this.b + c + d; } var o = {a: 1, b: 3}; // the first parameter is the object to use as // 'this', subsequent parameters are passed as // arguments in the function call add.call(o, 5, 7); // 16 // the first parameter is the object to use as // 'this', the second is an array whose // members are used as the arguments in the function call add.apply(o, [10, 20]); // 34 note that in non–strict mode, with call and apply, if the value passed as this is not an object, an attempt will be made to convert it to an object.
typeof - JavaScript
(logical not) operator are equivalent to boolean() // symbols typeof symbol() === 'symbol' typeof symbol('foo') === 'symbol' typeof symbol.iterator === 'symbol' // undefined typeof undefined === 'undefined'; typeof declaredbutundefinedvariable === 'undefined'; typeof undeclaredvariable === 'undefined'; // objects typeof {a: 1} === 'object'; // use array.isarray or object.prototype.tostring.call // to differentiate regular objects from arrays typeof [1, 2, 4] === 'object'; typeof new date() === 'object'; typeof /regex/ === 'object'; // see regular expressions section for historical results // the following are confusing, dangerous, and wasteful.
empty - JavaScript
see the following example with an empty loop body: let arr = [1, 2, 3]; // assign all array values to 0 for (let i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ; console.log(arr); // [0, 0, 0] unintentional usage it is a good idea to comment intentional use of the empty statement, as it is not really obvious to distinguish from a normal semicolon.
for await...of - JavaScript
the for await...of statement creates a loop iterating over async iterable objects as well as on sync iterables, including: built-in string, array, array-like objects (e.g., arguments or nodelist), typedarray, map, set, and user-defined async/sync iterables.
function* - JavaScript
; // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false } console.log(gen.next()); // { value: 3, done: false } console.log(gen.next()); // { value: undefined, done: true } generator as a computed property class foo { *[symbol.iterator] () { yield 1; yield 2; } } const someobj = { *[symbol.iterator] () { yield 'a'; yield 'b'; } } console.log(array.from(new foo)); // [ 1, 2 ] console.log(array.from(someobj)); // [ 'a', 'b' ] generators are not constructable function* f() {} var obj = new f; // throws "typeerror: f is not a constructor generator defined in an expression const foo = function* () { yield 10; yield 20; }; const bar = foo(); console.log(bar.next()); // {value: 10, done: false} generator example function* powers(n){ ...
throw - JavaScript
function userexception(message) { this.message = message; this.name = 'userexception'; } function getmonthname(mo) { mo = mo - 1; // adjust month number for array index (1 = jan, 12 = dec) var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; if (months[mo] !== undefined) { return months[mo]; } else { throw new userexception('invalidmonthno'); } } try { // statements to try var mymonth = 15; // 15 is out of bound to raise the exception var monthname = getmonthname(mymonth)...
Transitioning to strict mode - JavaScript
stay away from semantic differences eval: use it only if you know what you're doing arguments: always access function arguments via their name or perform a copy of the arguments object using: var args = array.prototype.slice.call(arguments) as the first line of your function this: only use this when it refers to an object you created.
JavaScript reference - JavaScript
deuri() decodeuricomponent() encodeuri() encodeuricomponent() fundamental objects object function boolean symbol error objects error aggregateerror evalerror internalerror rangeerror referenceerror syntaxerror typeerror urierror numbers & dates number bigint math date text processing string regexp indexed collections array int8array uint8array uint8clampedarray int16array uint16array int32array uint32array float32array float64array bigint64array biguint64array keyed collections map set weakmap weakset structured data arraybuffer sharedarraybuffer atomics dataview json control abstraction promise generator generatorfunction asyncfunction reflect...
categories - Web app manifests
type array of strings mandatory no the categories member is an array of strings defining the names of categories that the application supposedly belongs to.
icons - Web app manifests
type array mandatory yes the icons member specifies an array of objects representing image files that can serve as application icons for different contexts.
related_applications - Web app manifests
type array mandatory no the related_applications field is an array of objects specifying native applications that are installable by, or accessible to, the underlying platform — for example, a native android application obtainable through the google play store.
screenshots - Web app manifests
type object mandatory no the screenshots member defines an array of screenshots intended to showcase the application.
shortcuts - Web app manifests
type object mandatory no the shortcuts member defines an array of shortcuts or links to key tasks or pages within a web app.
Web app manifests
this splashscreen is auto-generated from properties in the web app manifest, specifically: name background_color the icon in the icons array that is closest to 128dpi for the device.
Media container formats (file types) - Web media technologies
on mac os, the quicktime framework not only supported quicktime format movie files and codecs, but supported a vast array of popular and specialty audio and video codecs, as well as still image formats.
Digital video concepts - Web media technologies
rgb most computer graphics models use the rgb color system, wherein some number of bits of data are used to represent each of the red, green, and blue components of the color of an individual pixel, and an image is comprised of a two-dimensional array of these pixels.
Navigation and resource timings - Web Performance
let navigationtimings = performance.getentriesbytype('navigation'); the performance.getentriesbytype('navigation')a returns an array of performanceentry objects for the navigation type.
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
if not, we initialize a new subscription: const response = await fetch('./vapidpublickey'); const vapidpublickey = await response.text(); const convertedvapidkey = urlbase64touint8array(vapidpublickey); the app fetches the server's public key and converts the response to text; then it needs to be converted to a uint8array (to support chrome).
Structural overview of progressive web apps - Progressive web apps (PWAs)
{ slug: 'emma-3d', name: 'emma-3d', author: 'prateek roushan', twitter: '', website: '', github: 'github.com/coderprateek/emma-3d' } ]; each entry in the array games describes a specific game, and has a corresponding image file in the data/img/ directory.
requiredFeatures - SVG: Scalable Vector Graphics
http://www.w3.org/tr/svg11/feature#basictext the browser supports the <text> element http://www.w3.org/tr/svg11/feature#paintattribute the browser supports the color, fill, fill-rule, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-width, color-interpolation and color-rendering attributes http://www.w3.org/tr/svg11/feature#basicpaintattribute the browser supports the color, fill, fill-rule, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-width and color-rendering attributes http://w...
<a> - SVG: Scalable Vector Graphics
WebSVGElementa
ng attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, document element event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility xlink attributes most notably: xlink:title aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disable...
<altGlyph> - SVG: Scalable Vector Graphics
WebSVGElementaltGlyph
notably: requiredextensions, systemlanguage event attributes global event attributes, document element event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, dominant-baseline, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, transform, vector-effect, visibility xlink attributes xlink:href, xlink:type, xlink:role, xlink:arcrole, xlink:title, xlink:show, xlink:actuate dom interface this element implements the svgaltglyphelement interface.
<circle> - SVG: Scalable Vector Graphics
WebSVGElementcircle
class, style conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<clipPath> - SVG: Scalable Vector Graphics
WebSVGElementclipPath
ingbox ; default value: userspaceonuse; animatable: yes global attributes core attributes most notably: id styling attributes class, style conditional processing attributes most notably: requiredextensions, systemlanguage presentation attributes most notably: clip-path, clip-rule, color, display, fill, fill-opacity, fill-rule, filter, mask, opacity, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility usage notes categoriesnonepermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elements<text>, <use> specifications specification status comment css masking module leve...
<defs> - SVG: Scalable Vector Graphics
WebSVGElementdefs
ibutes most notably: id lang styling attributes class, style event attributes global event attributes, document element event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility usage notes categoriescontainer element, structural elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-pro...
<ellipse> - SVG: Scalable Vector Graphics
WebSVGElementellipse
class, style conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<foreignObject> - SVG: Scalable Vector Graphics
: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes, document event attributes, document element event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<g> - SVG: Scalable Vector Graphics
WebSVGElementg
class, style conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<line> - SVG: Scalable Vector Graphics
WebSVGElementline
class, style conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<linearGradient> - SVG: Scalable Vector Graphics
global attributes core attributes most notably: id styling attributes class, style event attributes global event attributes, document element event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility xlink attributes xlink:href, xlink:title usage notes categoriesgradient elementpermitted contentany number of the following elements, in any order:descriptive elements<animate>, <animatetransform>, <set>, <stop> specifications specification ...
<marker> - SVG: Scalable Vector Graphics
WebSVGElementmarker
tes core attributes most notably: id, tabindex styling attributes class, style conditional processing attributes most notably: requiredextensions, systemlanguage presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<mask> - SVG: Scalable Vector Graphics
WebSVGElementmask
e type: <length> ; default value: 120%; animatable: yes global attributes core attributes most notably: id styling attributes class, style conditional processing attributes most notably: requiredextensions, systemlanguage presentation attributes most notably: clip-path, clip-rule, color, display, fill, fill-opacity, fill-rule, filter, mask, opacity, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility usage notes categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef>, <clippath>, <color-profile>, <cursor>, <fi...
<path> - SVG: Scalable Vector Graphics
WebSVGElementpath
class, style conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<pattern> - SVG: Scalable Vector Graphics
WebSVGElementpattern
tes core attributes most notably: id, tabindex styling attributes class, style conditional processing attributes most notably: requiredextensions, systemlanguage presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility xlink attributes most notably: xlink:title usage notes categoriescontainer elementpermitted contentany number of the following elements, in any order:animation elementsdescriptive elementsshape elementsstructural elementsgradient elements<a>, <altglyphdef...
<polygon> - SVG: Scalable Vector Graphics
WebSVGElementpolygon
class, style conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<polyline> - SVG: Scalable Vector Graphics
WebSVGElementpolyline
class, style conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<radialGradient> - SVG: Scalable Vector Graphics
global attributes core attributes most notably: id styling attributes class, style event attributes global event attributes, document element event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility xlink attributes xlink:href, xlink:title usage notes categoriesgradient elementpermitted contentany number of the following elements, in any order:descriptive elements<animate>, <animatetransform>, <set>, <stop> specifications specification ...
<rect> - SVG: Scalable Vector Graphics
WebSVGElementrect
class, style conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<svg> - SVG: Scalable Vector Graphics
WebSVGElementsvg
: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes, document event attributes, document element event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<symbol> - SVG: Scalable Vector Graphics
WebSVGElementsymbol
attributes most notably: id styling attributes class, style event attributes global event attributes, document element event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<text> - SVG: Scalable Vector Graphics
WebSVGElementtext
itional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, dominant-baseline, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errorme...
<textPath> - SVG: Scalable Vector Graphics
WebSVGElementtextPath
class, style conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
<tspan> - SVG: Scalable Vector Graphics
WebSVGElementtspan
itional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, dominant-baseline, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, text-anchor, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errorme...
<use> - SVG: Scalable Vector Graphics
WebSVGElementuse
class, style conditional processing attributes most notably: requiredextensions, systemlanguage event attributes global event attributes, graphical event attributes presentation attributes most notably: clip-path, clip-rule, color, color-interpolation, color-rendering, cursor, display, fill, fill-opacity, fill-rule, filter, mask, opacity, pointer-events, shape-rendering, stroke, stroke-dasharray, stroke-dashoffset, stroke-linecap, stroke-linejoin, stroke-miterlimit, stroke-opacity, stroke-width, transform, vector-effect, visibility aria attributes aria-activedescendant, aria-atomic, aria-autocomplete, aria-busy, aria-checked, aria-colcount, aria-colindex, aria-colspan, aria-controls, aria-current, aria-describedby, aria-details, aria-disabled, aria-dropeffect, aria-errormessage, aria-e...
SVG element reference - SVG: Scalable Vector Graphics
WebSVGElement
« svg / svg attribute reference » svg drawings and images are created using a wide array of elements which are dedicated to the construction, drawing, and layout of vector images and diagrams.
Using custom elements - Web Components
this is done by specifying a static get observedattributes() method inside custom element class - this should return an array containing the names of the attributes you want to observe: static get observedattributes() { return ['c', 'l']; } this is placed right at the top of the constructor, in our example.