En javascript, si creo una matriz const, aún puedo modificar el objeto al que apunta la variable:
// The const declaration creates a read-only reference to a value. // It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const const x = [1,2,3]; x.push(4); console.log(x); x=55 // But this is illegal and will error console.log(x); ¿Hay alguna manera de hacer que los elementos de una matriz también sean inmutables? Similar a algo como const int* const x; ¿Cía?
Puede usar Object.freeze para evitar que se cambie un objeto (o una matriz):
const x = [1, 2, 3]; Object.freeze(x); x.push(4); // This will throw an exceptionlos objetos congelados con Object.freeze() se vuelven inmutables.
Aquí están los documentos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
Ejemplo:
const x = [1,2,3]; Object.freeze(x);